<?php
/**
 * Created by PhpStorm.
 * User: g
 * Date: 2018/1/19
 * Time: 14:31
 */

namespace app\index\controller;
use app\index\validate\Valid;
use think\Request;
use Think\Db;

class Workflowdb extends Common
{
    //待办列表
    public function index(){

        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['requestType'] = 'TodoList';
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/todo/page.wf?page='.$page.'&limit=100',$post_data);
//        dump($data);
        if(!$data){
            echo "无工作流";die;
        }
        if(!isset($data->data)||!is_array($data->data)){
            echo '';
        }
        foreach($data->data as $k=>$v){
            $workId = $v->workId;
            $v->myId = db('cg_workflow')->where('workId',$workId)->value('id');
            $v->ywlx = db('cg_workflow')->where(['workId'=>$v->workId])->value('ywlx');
            $v->rwmcjbh = db('cg_workflow')->where(['workId'=>$v->workId])->value('rwmcjbh');
            $v->status = db('cg_workflow')->where(['workId'=>$v->workId])->value('status');
            $v->arrive_time = db('cg_workflow')->where(['workId'=>$v->workId])->value('arrive_time');
            $v->department_id = db('cg_workflow')->where(['workId'=>$v->workId])->value('department_id');
            $v->sqr_id = db('cg_workflow')->where(['workId'=>$v->workId])->value('sqr_id');
            $v->type = db('cg_workflow_ywlx')->where('id',$v->ywlx)->value('title');
            $v->department = db('department')->where('id',$v->department_id)->value('de_name');
            $v->sqr = db('employee')->where('id',$v->sqr_id)->value('em_name');
            $data->data[$k] = $v;
        }
        $data->data = $this->object_array($data->data);
        $this->assign('data',$data->data);
        $this->assign('page',$page);

        //查询业务类型
        $ywlx = db('cg_workflow_ywlx')->select();
        $this->assign('ywlx',$ywlx);
        return $this->fetch();
    }// $data ywlx

    //待阅列表
    public function matterread(){
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['requestType'] = 'MatterRead';
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/todo/page.wf?page='.$page.'&limit=10',$post_data);
//        dump($data);
        if(!$data){
            echo "无工作流";die;
        }
        if(!isset($data->data)||!is_array($data->data)){
            echo '';
        }
        foreach($data->data as $k=>$v){
            $workId = $v->workId;
            $v->myId = db('cg_workflow')->where('workId',$workId)->value('id');
            $v->ywlx = db('cg_workflow')->where(['workId'=>$v->workId])->value('ywlx');
            $v->rwmcjbh = db('cg_workflow')->where(['workId'=>$v->workId])->value('rwmcjbh');
            $v->status = db('cg_workflow')->where(['workId'=>$v->workId])->value('status');
            $v->arrive_time = db('cg_workflow')->where(['workId'=>$v->workId])->value('arrive_time');
            $v->department_id = db('cg_workflow')->where(['workId'=>$v->workId])->value('department_id');
            $v->sqr_id = db('cg_workflow')->where(['workId'=>$v->workId])->value('sqr_id');
            $v->type = db('cg_workflow_ywlx')->where('id',$v->ywlx)->value('title');
            $v->department = db('department')->where('id',$v->department_id)->value('de_name');
            $v->sqr = db('employee')->where('id',$v->sqr_id)->value('em_name');
            $data->data[$k] = $v;
        }
        $data->data = $this->object_array($data->data);
        $this->assign('data',$data->data);
        $this->assign('page',$page);

        //查询业务类型
        $ywlx = db('cg_workflow_ywlx')->select();
        $this->assign('ywlx',$ywlx);
        return $this->fetch();
    }

    //已阅列表
    public function hadread(){
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['requestType'] = 'HadRead';
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/haddone/page.wf?page='.$page.'&limit=10',$post_data);
//        dump($data);
        if(!$data){
            echo "无工作流";die;
        }
        if(!isset($data->data)||!is_array($data->data)){
            echo '';
        }
        foreach($data->data as $k=>$v){
            $workId = $v->workId;
            $v->myId = db('cg_workflow')->where('workId',$workId)->value('id');
            $v->ywlx = db('cg_workflow')->where(['workId'=>$v->workId])->value('ywlx');
            $v->rwmcjbh = db('cg_workflow')->where(['workId'=>$v->workId])->value('rwmcjbh');
            $v->status = db('cg_workflow')->where(['workId'=>$v->workId])->value('status');
            $v->arrive_time = db('cg_workflow')->where(['workId'=>$v->workId])->value('arrive_time');
            $v->department_id = db('cg_workflow')->where(['workId'=>$v->workId])->value('department_id');
            $v->sqr_id = db('cg_workflow')->where(['workId'=>$v->workId])->value('sqr_id');
            $v->type = db('cg_workflow_ywlx')->where('id',$v->ywlx)->value('title');
            $v->department = db('department')->where('id',$v->department_id)->value('de_name');
            $v->sqr = db('employee')->where('id',$v->sqr_id)->value('em_name');
            $data->data[$k] = $v;
        }
        $data->data = $this->object_array($data->data);
        $this->assign('data',$data->data);
        $this->assign('page',$page);

        //查询业务类型
        $ywlx = db('cg_workflow_ywlx')->select();
        $this->assign('ywlx',$ywlx);
        return $this->fetch();
    }

    //已办列表
    public function ybindex(){
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['requestType'] = 'HadDone';
        $page = $this->request->param('page')?$this->request->param('page'):1;
        $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/haddone/page.wf?page='.$page.'&limit=10',$post_data);
//        dump($data);
        foreach($data->data as $k=>$v){
            $workId = $v->workId;
            $v->myId = db('cg_workflow')->where('workId',$workId)->value('id');
            $v->ywlx = db('cg_workflow')->where(['workId'=>$v->workId])->value('ywlx');
            $v->rwmcjbh = db('cg_workflow')->where(['workId'=>$v->workId])->value('rwmcjbh');
            $v->status = db('cg_workflow')->where(['workId'=>$v->workId])->value('status');
            $v->arrive_time = db('cg_workflow')->where(['workId'=>$v->workId])->value('arrive_time');
            $v->department_id = db('cg_workflow')->where(['workId'=>$v->workId])->value('department_id');
            $v->sqr_id = db('cg_workflow')->where(['workId'=>$v->workId])->value('sqr_id');
            $v->type = db('cg_workflow_ywlx')->where('id',$v->ywlx)->value('title');
            $v->department = db('department')->where('id',$v->department_id)->value('de_name');
            $v->sqr = db('employee')->where('id',$v->sqr_id)->value('em_name');
            $data->data[$k] = $v;
        }

        $data->data = $this->object_array($data->data);
        $this->assign('data',$data->data);
        $this->assign('page',$page);
        return $this->fetch();
    }

    //查看流程图
    public function workflowchart(){
        $id = $this->request->param('id');
        $workId = db('cg_workflow')->where(['id'=>$id])->value('workId');
        $trackId = db('cg_workflow')->where(['id'=>$id])->value('trackId');//dump($workId);dump($trackId);
        //echo config('workflow_url').'/horizon/workflow/module/workflow/flowchart.jsp?workId='.$workId.
          //  '&trackId='.$trackId;die;
       // header('location:'.config('workflow_url').'/horizon/workflow/module/workflow/flowchart.jsp?workId='.$workId.
        //    '&trackId='.$trackId);
         header('location:'.config('workflow_url').'/workflow/module/workflow/flow.info.html?workId='.$workId.
            '&trackId='.$trackId);
    }

    //对象转成数组
    function object_array($array) {
        if(is_object($array)) {
            $array = (array)$array;
        } if(is_array($array)) {
            foreach($array as $key=>$value) {
                $array[$key] = $this->object_array($value);
            }
        }
        return $array;
    }

    //处理
    public function process(){
        $workId = $this->request->param('workId');
        $trackId = $this->request->param('trackId');

        if($_POST){
            $nodeId = $this->request->post('nodeId');
            $actionData = [
                'operate'=>'submit',
                'operateClazz'=>'com.horizon.wf.action.ActionSubmit',
                'operateText'=>'提 交',
                'operateFlag'=>1,
            ];
            $param = [
                'accessToken'=>session("accessToken"),
                'workId'=>$workId,
                'trackId'=>$trackId,
                'nodeId'=>$nodeId,
                'actionData'=>$actionData,
            ];
            $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/action.wf',$param);
            dump($data);
            return $this->fetch('xzblr');
            die;
        }
        //打开工作流
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['workId'] = $workId;
        $post_data['trackId'] = $trackId;
        $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$post_data);
        $this->assign('data',$data);
        return $this->fetch();
    }
      //获取按钮
    public function getbton($fid,$aid){


        $flow = db('cg_workflow')->where(["ywlx"=>$fid,"yw_id"=>$aid])->field("trackId,workId")->find();
        $workId=$flow["workId"];$trackId=$flow["trackId"];$nodeId="End1";

         //打开工作流
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['workId'] = $workId;
        $post_data['trackId'] = $trackId;
        $dataopen = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$post_data);


        $actionData = [
                    'operate'=>'submit',
                    'operateClazz'=>'com.horizon.wf.action.ActionSubmit',
                    'operateText'=>'提 交',
                    'operateFlag'=>1,
                ];
                $param = [
                    'accessToken'=>session("accessToken"),
                    'workId'=>$workId,
                    'trackId'=>$trackId,
                    
                    'actionData'=>$actionData,
                ];
        $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/action.wf',$param);
        $data = object_array($data);
       // print_r($data["nextNodes"]);
        return $data;
    }
    //取消审核
    public function qxshenhe($from=1,$aid=''){
        if($aid){
            $yw_id=$aid;
        }else{
            $workId = $this->request->param('workId');
            $trackId = $this->request->param('trackId');
            $myId = $this->request->param('myId');
            $yw_id =db('cg_workflow')->where('id',$myId)->value('yw_id');
        }
        $type_id=db("cg_ti")->where(["id"=>$yw_id])->value("type_id");
        $this->assign("type_id",$type_id);
        $this->assign("yw_id",$yw_id);
        $status=db("cg_ti")->where(["id"=>$yw_id])->value("status");
        if($status==2){
            $btn=$this->getbton(22,$yw_id);
            $this->assign("btn",$btn);
            //print_r($btn);exit;
        }
        $this->assign("status",$status);
        $this->assign("from",$from);
        return $this->fetch();
    }
    //异动审核
    public function ydshenhe($from=1,$aid=''){
        if($aid){
            $yw_id=$aid;
        }else{
            $workId = $this->request->param('workId');
            $trackId = $this->request->param('trackId');
            $myId = $this->request->param('myId');
            $yw_id =db('cg_workflow')->where('id',$myId)->value('yw_id');
        }
        
        
        $type_id=db("cg_ti")->where(["id"=>$yw_id])->value("type_id");
        $this->assign("type_id",$type_id);
        $this->assign("yw_id",$yw_id);
        $status=db("cg_ti")->where(["id"=>$yw_id])->value("status");
        if($status==2){
            $btn=$this->getbton(21,$yw_id);
            $this->assign("btn",$btn);
            //print_r($btn);exit;
        }
        $this->assign("status",$status);
        $this->assign("from",$from);
        return $this->fetch();//$ type_id
    }

    //new异动审核
    public function newydshenhe($from=1,$aid=''){
        //echo '1';
        if($aid){
           // echo '2';
            $yw_id=$aid;
        }else{
            $workId = $this->request->param('workId');
            $trackId = $this->request->param('trackId');
            $myId = $this->request->param('myId');
            $yw_id =db('cg_workflow')->where('id',$myId)->value('yw_id');
          //  echo '3';
        }


        $type_id=db("cg_ti")->where(["id"=>$yw_id])->value("type_id");
        //echo '4';
       // echo $type_id;die;
        $this->assign("type_id",$type_id);
        $this->assign("yw_id",$yw_id);
        $status=db("cg_ti")->where(["id"=>$yw_id])->value("status");
        //echo '5';
        if($status==2){
            $btn=$this->getbton(21,$yw_id);
            $this->assign("btn",$btn);
            //print_r($btn);exit;
        }
        //echo '6';die;  // type_id
        $this->assign("status",$status);
        $this->assign("from",$from);
        return $this->fetch();
    }

     //自动提交
    public function goworker($fid,$aid,$nodeKey,$selectId,$selectName){
        $flow = db('cg_workflow')->where(["ywlx"=>$fid,"yw_id"=>$aid])->field("trackId,workId")->find();
        $workId=$flow["workId"];$trackId=$flow["trackId"];
       
         $actionData = [
                    'operate'=>'submit',
                    'operateClazz'=>'com.horizon.wf.action.ActionSubmit',
                    'operateText'=>'提 交',
                    'operateFlag'=>0,
                    'nextNodes'=>[
                        [
                            'nodeKey'=>$nodeKey,
                            'selectId'=>$selectId,
                            'selectName'=>$selectName,
                            'isSelect'=>"true",
                            
                        ]
                    ],
                    "subFlows"=>null
                ];
                $param = [
                    'accessToken'=>session("accessToken"),
                    'workId'=>$workId,
                    'trackId'=>$trackId,
                    'actionData'=>$actionData,
                    "comment"=>"",
                    "dataId"=>"",
                ];
        $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/action.wf',$param);

        $data = object_array($data);
        return $data;
    }
    public function qxzuofeichuli(){
        $request = Request::instance();$data = $request->post();
        
        //print_r($data);exit;
        $fid=22;$aid=$data["aid"];
          $res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
         if($res["operateStatus"]=="success"){
                $yuanid=Db::table("cg_ti")->where(["id"=>$aid])->value("old");
                $updata["id"]=$aid;
                $updata["status"]=8;
                
                Db::startTrans();
            try{
                
            
                $res1=Db::table("cg_ti")->update($updata);
                // Db::rollBack();return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                if($yuanid){
                    Db::table("cg_ti")->where(["id"=>$yuanid])->update(["is_ydqx"=>0]);
                }
                
            }catch(\Exception $e){
                //echo $e->getMessage();
                Db::rollBack();
               return json_encode(["msg"=>$e->getMessage(),"state"=>2]);
            }
             if($res1){

                Db::commit();
            

                return json_encode(["msg"=>"","state"=>1]);
            }else{
                Db::rollBack();
              return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            }
            }else{
                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            }
    }  
    public function ydzuofeichuli(){
        $request = Request::instance();$data = $request->post();
        
        //print_r($data);exit;
        $fid=21;$aid=$data["aid"];
        $res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
        //$res["operateStatus"]="success";
            if($res["operateStatus"]=="success"){
                $yuanid=Db::table("cg_ti")->where(["id"=>$aid])->value("old");
                $updata["id"]=$aid;
                $updata["status"]=8;
                
                Db::startTrans();
            try{
                
            
                $res1=Db::table("cg_ti")->update($updata);
                // Db::rollBack();return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
                if($yuanid){
                    Db::table("cg_ti")->where(["id"=>$yuanid])->update(["is_ydqx"=>0]);
                }
                 $ys=Db::table("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("y.type=1 and yd.aid=$aid")->field("yd.id")->select();
                  if($ys){
                    $ysarr=[];
                    for($i=0;$i<count($ys);$i++){
                      $ysarr[]=$ys[$i]["id"];
                    }
                    $ysarr=implode(',',$ysarr);
                    db("yusuan_detail")->where("id in($ysarr)")->delete();
                  }
            }catch(\Exception $e){
                //echo $e->getMessage();
                Db::rollBack();
               return json_encode(["msg"=>$e->getMessage(),"state"=>2]);
            }
             if($res1){

                Db::commit();
            

                return json_encode(["msg"=>"","state"=>1]);
            }else{
                Db::rollBack();
              return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            }
            }else{
                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            }
        
    }
    //非常规促销费用申请
    public function noformalbacklogdetail(){
        $workId = $this->request->param('workId');
        $trackId = $this->request->param('trackId');
        $myId = $this->request->param('myId');
        //yw_id
        $yw_id =db('cg_workflow')->where('id',$myId)->value('yw_id');
        $this->assign('yw_id',$yw_id);
        $state=db("cg_ti")->where(["id"=>$yw_id])->value("status");
        if($state==2){
             //打回
            $this->redirect('TiApply2/update', ['id' => $yw_id,"from"=>2]);
            return;
        }
        if($_POST){
            $type = $this->request->post('type');
            if($type==1){ //选定办理人
                $nodeId = $this->request->post('nodeId');
                $data = $this->request->post('data');
                $selectAuthor = $this->request->post('Author');
                $selectAuthorName = db('users t')->join('employee t2','t.employee_id=t2.id')->where('t.id',$selectAuthor)->value('t2.em_name');
                $data = json_decode($data);
                $data = $this->object_array($data);
                $xdjd = [];
                foreach($data['nextNodes'] as $k=>$v){
                        $v['isSelect'] = "true";
                        $data['nextNodes'][$k] = $v;
                        $xdjd = $v;
                }

                $actionData = [
                    'operate'=>'submit',
                    'operateClazz'=>'com.horizon.wf.action.ActionSubmit',
                    'operateText'=>'提 交',
                    'operateFlag'=>0,
                    'nextNodes'=>[
                        [
                            'nodeKey'=>$xdjd['nodeKey'],
                            'selectId'=>$xdjd['selectId'],
                            'selectName'=>$xdjd['selectName'],
                            'isSelect'=>$xdjd['isSelect'],
                            'authors'=>[
                                'Author'=>[
                                    'authorId'=>'Author',
                                    'selectAuthor'=>$selectAuthor,
                                    'selectAuthorName'=>$selectAuthorName,
                                ]
                            ],
                            'nodeId'=>$data['nextNodes'][0]['nodeId'],
                            'nodeName'=>$data['nextNodes'][0]['nodeName'],
                        ]
                    ],
                    "subFlows"=>null
                ];
                $param = [
                    'accessToken'=>session("accessToken"),
                    'workId'=>$workId,
                    'trackId'=>$trackId,
                    'nodeId'=>$nodeId,
                    'actionData'=>$actionData,
                    "comment"=>"",
                    "dataId"=>"",
                ];
                $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/action.wf',$param);

                if($data['operateMsg']=='提交成功'){
                    $spyj = $this->request->post('spyj');
                    db('cg_workflow_spyj')->insert([
                        'spr_id'=>session('employee_id'),
                        'spr_name'=>db('employee')->where('id',session('employee_id'))->value('em_name'),
                        'spr_job'=>db('job t')->join('job_employee t2','t2.job_id=t.id')->where('t2.employee_id',session('employee_id'))->value('t.job_name'),
                        'wf_id'=>$myId,
                        'spyj'=>$spyj,
                        'spdz'=>$xdjd['nodeName'],
                        'spsj'=>date('Y-m-d H:i:s')
                    ]);

                    //$xdjd['nodeName']或者$data['nextNodes'][0]['nodeName'];
                    db('cg_ti')->where('id',$yw_id)->update(['status'=>$xdjd['nodeName']]);

                    $this->redirect('index');
                }else{
                    echo $data['operateMsg'];
                }
                die;
            }elseif($type==2){ //选定节点
                $data = $this->request->post('data');
                $nodeId = $this->request->post('node');
                $data = json_decode($data);
                $data = $this->object_array($data);
                $spyj = $this->request->post('spyj');
                $this->assign('spyj',$spyj);
                $xdjd = [];
                foreach($data['nextNodes'] as $k=>$v){
                    if($v['nodeId'] == $nodeId){
                        $v['isSelect'] = "true";
                        $data['nextNodes'][$k] = $v;
                        $xdjd = $v;
                    }

                }
                $nodeId = $data['nodeId'];

                $nextNodes = [[
                    'nodeKey'=>$xdjd['nodeKey'],
                    'selectId'=>$xdjd['selectId'],
                    'selectName'=>$xdjd['selectName'],
                    'isSelect'=>$xdjd['isSelect']
                ]];
                $actionData = [
                    'operate'=>'submit',
                    'operateClazz'=>'com.horizon.wf.action.ActionSubmit',
                    'operateText'=>'提 交',
                    'operateFlag'=>1,
                    'nextNodes'=>$nextNodes
                ];
                $param = [
                    'accessToken'=>session("accessToken"),
                    'workId'=>$workId,
                    'trackId'=>$trackId,
                    'nodeId'=>$nodeId,
                    'actionData'=>$actionData,
                ];
                $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/action.wf',$param);

                $data = object_array($data);
                $this->assign('data',$data);
                return $this->fetch('xzblr');
            }else{
                $nodeId = $this->request->post('nodeId');
                $spyj = $this->request->post('spyj');
                $this->assign('spyj',$spyj);
                $actionData = [
                    'operate'=>'submit',
                    'operateClazz'=>'com.horizon.wf.action.ActionSubmit',
                    'operateText'=>'提 交',
                    'operateFlag'=>1,
                ];
                $param = [
                    'accessToken'=>session("accessToken"),
                    'workId'=>$workId,
                    'trackId'=>$trackId,
                    'nodeId'=>$nodeId,
                    'actionData'=>$actionData,
                ];
                $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/action.wf',$param);

                $data = object_array($data);
                $this->assign('data',$data);
                if($data['operateMsg'] == '请从列表中选择节点'){
                    return $this->fetch('xzjd');
                }else{
                    return $this->fetch('xzblr');
                }
            }
            die;
        }
        //打开工作流
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['workId'] = $workId;
        $post_data['trackId'] = $trackId;
        $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$post_data);
        $data = object_array($data);
        $this->assign('data',$data);

        $info = db('cg_ti')->where('id',$yw_id)->find();
        $info['jxs_name'] = db('cg_jxs')->where('id',$info['jxs_id'])->value('title');
        $info['sqr'] = db('employee')->where('id',$info['cuser'])->value('em_name');
        $info['sqr_job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->where('t2.employee_id',$info['cuser'])->value('t.job_name');
        $info['zoning'] = db('cg_market_zoning t')->join('cg_jxs t2','t2.zoning=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['provice'] = db('cg_market_provice t')->join('cg_jxs t2','t2.provice=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['city'] = db('cg_market_city t')->join('cg_jxs t2','t2.city=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['jxs_type'] = db('cg_jxs_types t')->join('cg_jxs t2','t2.types=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['start'] = db('cg_ti_list')->where('ti_id',$yw_id)->value('start');
        $info['end'] = db('cg_ti_list')->where('ti_id',$yw_id)->value('end');

        if($info['productlat']==1){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'brand'=>['exp','is not null']])->value('brand');
            $info['pro_label'] = '品牌';
            $info['pro_name'] = db('pro_brands')->where('id',$brand_id)->value('brand_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->group("brand")->count('brand');
        }elseif($info['productlat']==2){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'category'=>['exp','is not null']])->value('category');
            $info['pro_label'] = '品类';
            $info['pro_name'] = db('pro_category')->where('id',$brand_id)->value('category_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->group("category")->count('category');
        }elseif($info['productlat']==3){
            $info['pro_label'] = '系列';
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'series'=>['exp','is not null']])->value('series');
            $info['pro_name'] = db('pro_series')->where('id',$brand_id)->value('series_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->group("series")->count('series');
        }elseif($info['productlat']==4){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'sku'=>['exp','is not null']])->value('sku');
            $info['pro_label'] = 'sku';
            $info['pro_name'] = db('pro_sku')->where('id',$brand_id)->value('sku_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->group("sku")->count('sku');
        }elseif($info['productlat']==5){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'product'=>['exp','is not null']])->value('product');
            $info['pro_label'] = '产品';
            $info['pro_name'] = db('pro_products')->where('id',$brand_id)->value('pro_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->group("product")->count('product');
        }

        //费用类型
        $info['fylx'] = Db::query('select count(*) cnt from (select feetype from cg_ti_list where ti_id='.$yw_id.' group by feetype) t')[0]['cnt'];
        $info['fylx_name'] = db('cg_ti_list t')->join('cg_feiyongkemu3 t2','t2.id=t.feetype')->where('ti_id',$yw_id)->value('t2.title');
        $info['fye'] = round(db('cg_ti_list')->where(['ti_id'=>$yw_id])->sum('yjsjtrfy'),2);
        $info['xl'] = round(db('cg_ti_list')->where(['ti_id'=>$yw_id])->sum('totalExpectedSales'),2);
        $info['fyl'] = round($info['fye']/$info['xl']*100,2);
        $gs = db('cg_ti_list')->where(['ti_id'=>$yw_id])->count();
        $yujiroi = db('cg_ti_list')->where(['ti_id'=>$yw_id])->sum('yujiroi');
        $info['roi'] = round($yujiroi/$gs,2);

        //查看活动是否重复--判断是否存在费用类型相同收款方也相同的情况
        /*$cnt1 = Db::query('SELECT count(*) cnt from (SELECT gys,count(gys) AS count FROM cg_ti_list where ti_id='.$yw_id.' and gys is not null GROUP BY feetype,payee HAVING count > 1) t');
        $cnt1 = $cnt1[0]['cnt'];

        $info['iscf'] =$cnt1;*/

        $this->assign('info',$info);

        /**
         *问题点--start
         */
        $wtd = [];$checkwt["fyl"]=0;$checkwt["roi"]=0;$checkwt["fanwei"]=0;$checkwt["ys"]=0;
        //公司建议的TI活动最高费用率值
        $feiYongLv = db('system_param')->where(['t'=>0,'k'=>'feiYongLv'])->value('v');
        if($info['fyl']>$feiYongLv){
            $checkwt["fyl"]=1;
            $wtd[] = '本申请单费用率不符合公司规定，公司规定为：'.$feiYongLv.'%';
        }
        //公司建议的TI活动ROI合格值
        $minRoi = db('system_param')->where(['t'=>0,'k'=>'minRoi'])->value('v');
        if($info['roi']<$minRoi){
            $wtd[] = '本申请单ROI低于公司规定，公司规定最小值为：'.$minRoi.'%';
            $checkwt["roi"]=1;
        }
        //公司建议的TI活动ROI较优值
        $maxRoi = db('system_param')->where(['t'=>0,'k'=>'maxRoi'])->value('v');
        if($info['roi']>$maxRoi){
            $wtd[] = '本申请单ROI高于公司规定，公司规定最大值为：'.$maxRoi.'%';
            $checkwt["roi"]=2;
        }

        /**
         *问题点--end
         */
        $applyde=db("cg_ti_list")->where(["ti_id"=>$yw_id])->select();
        //运算按照明细合并
        $yusuan=Db::table("yusuan_detail")->alias("yd")->join("yusuan y","yd.yid=y.id")
        ->where(["yd.aid"=>$yw_id,"y.type"=>1])->group("yd.did")->field("yd.aid,yd.did,sum(yd.jine) as jine,sum(yd.tianshu) as tianshu,max(yd.zongtianshu) as zongtianshu")
        ->select();
        
        $flag1=0;//是否所有明细都有匹配预算
       
        if(count($applyde)>count($yusuan)){
           $flag1=1;
        }
        
        for($i=0;$i<count($yusuan);$i++){
            if($yusuan[$i]["tianshu"]<$yusuan[$i]["zongtianshu"]){
                $flag1=1;
            }
        }
        if($flag1==1){
            $checkwt["ys"]=1;//未设定预算
            $wtd[] ="本申请中存在未设定预算的明细";
        }
        $flag2=0;//超出预算情况
        $yusuande=Db::table("yusuan_detail")->alias("yd")->join("yusuan y","yd.yid=y.id")
        ->where(["yd.aid"=>$yw_id,"y.type"=>1])->group("y.id")->field("y.id,y.jine,sum(yd.jine) as sjine,y.yijikaoheqi,y.erjikaoheqi,y.cainian,y.channel1,y.pinpai,y.erjifeiyong")->select();
         //预算明细处理

        for($i=0;$i<count($yusuande);$i++){
            //已通过预算的使用金额
           $yusuande[$i]["ytongguo"]=round(Db::table("yusuan_detail")->where(["yid"=>$yusuande[$i]["id"],"type"=>2])->sum("jine"),2);
           if(!$yusuande[$i]["ytongguo"])
                $yusuande[$i]["ytongguo"]=0;
            
           //申请中的预算使用金额
           $yusuande[$i]["shenqingzhong"]=round(Db::table("yusuan_detail")->where(["yid"=>$yusuande[$i]["id"],"type"=>1])->sum("jine"),2);
           if(!$yusuande[$i]["shenqingzhong"])
                $yusuande[$i]["shenqingzhong"]=0;
           if($yusuande[$i]["ytongguo"]>=$yusuande[$i]["jine"]){
                $yusuande[$i]["deng"]=2;
                $flag2=2;
           }else if($yusuande[$i]["ytongguo"]+$yusuande[$i]["shenqingzhong"]>$yusuande[$i]["jine"]){
                $yusuande[$i]["deng"]=1;
                if($flag2<2)
                    $flag2=1;
           }else{
                $yusuande[$i]["deng"]=0;
           }
            
            $yusuande[$i]["cainian"]=Db::table("cg_cainian")->where(["id"=>$yusuande[$i]["cainian"]])->value("title");
            if($yusuande[$i]["erjikaoheqi"]){
                
                $yusuande[$i]["kaoheqi"]=Db::table("cg_kaoheqi2")->where(["id"=>$yusuande[$i]["erjikaoheqi"]])->value("title");
            }else{
               
                $yusuande[$i]["kaoheqi"]=Db::table("cg_kaoheqi1")->where(["id"=>$yusuande[$i]["yijikaoheqi"]])->value("title");
            }
            $yusuande[$i]["channel"]=Db::table("cg_channel_types1")->where(["id"=>$yusuande[$i]["channel1"]])->value("title");
            $yusuande[$i]["pinpai"]=Db::table("pro_brands")->where(["id"=>$yusuande[$i]["pinpai"]])->value("brand_name");
            $yusuande[$i]["erjifeiyong"]=Db::table("cg_feiyongkemu2")->where(["id"=>$yusuande[$i]["erjifeiyong"]])->value("title");
            $yusuande[$i]["weiyong"]=round($yusuande[$i]["jine"]-$yusuande[$i]["ytongguo"],2);
            $yusuande[$i]["sjine"]=round($yusuande[$i]["sjine"],2);
        }
        if($flag2==1){
            $checkwt["ys"]=2;//未设定预算
            $wtd[] ="本申请中存在预算申请将超预算的情况";
        }else if($flag2==2){
            $checkwt["ys"]=3;//未设定预算
            $wtd[] ="本申请中存在预算申请已超预算的情况";
        }
        $this->assign("yusuande",$yusuande);$this->assign("checkwt",$checkwt);$this->assign("wtd",$wtd);
        /**
         * 活动列表--start
         */
        $heji["xl"]=0;$heji["jizhun"]=0;$heji["fy"]=0;
        $ti_list = db('cg_ti_list')->where('ti_id',$yw_id)->field('start,end,feetype,product,brand,category,series,sku,yjsjtrfy,totalExpectedSales,paymethod,yujiroi,totalBenchmarkSales')->select();
        foreach($ti_list as $k=>$v){
            $v['feetype_name'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
            if($v['product'])
                $v['product_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
            elseif($v['brand'])
                $v['product_name'] = db('pro_brands')->where('id',$v['brand'])->value('brand_name');
            elseif($v['category'])
                $v['product_name'] = db('pro_category')->where('id',$v['category'])->value('category_name');
            elseif($v['series'])
                $v['product_name'] = db('pro_series')->where('id',$v['series'])->value('series_name');
            elseif($v['sku'])
                $v['product_name'] = db('pro_sku')->where('id',$v['sku'])->value('sku_name');
            $v['yjfyl'] = round($v['yjsjtrfy']/$v['totalExpectedSales']*100,2);
            $v['zffs'] = db('cg_paymethod')->where('id',$v['paymethod'])->value('title');
            $ti_list[$k] = $v;
            $heji["xl"]+=$v['totalExpectedSales'];$heji["jizhun"]+=$v['totalBenchmarkSales'];$heji["fy"]+=$v['yjsjtrfy'];
        }
        $this->assign('ti_list',$ti_list);$this->assign("heji",$heji);
        /**
         * 活动列表--end
         */

        //本次申请已耗时
        $time = time()-$info['ctime'];
        $bcsqhs = $this->vtime($time);
        $this->assign('bcsqhs',$bcsqhs);

        //获取操作记录
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['workId'] = $workId;
        $czjl = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/history.wf',$post_data);
        $czjl = object_array($czjl);
//        echo "<pre>";print_r($czjl);
        foreach($czjl as $k=>$v){
            //查询审批意见
            $wf_id = 0;
//            $v['spyj'] = db('cg_workflow_spyj')->where(['wf_id'=>$wf_id,'spr_id']);
        }
        $this->assign('czjl',$czjl);

        //查询附件
        $attachs = db('cg_workflow_spyj')->where('wf_id',$myId)->column('attach');
        if($attachs){
            $attach = [];
            foreach($attachs as $item){
                if($item){
                    $item = unserialize($item);
                    foreach($item as $k=>$v){
                        $temp = Db::table('annex')->where(array('id'=>$v))->find();
                        $temp['path'] = '/uploads/'.$temp['path'];
                        $item[$k] = $temp;
                    }
                    $attach = array_merge($attach,$item);
                }
            }

            $this->assign('attach',$attach);

        }
         //按照三级费用科目查询
        $sjfykm = db('cg_ti_list')->where('ti_id', $yw_id)->field('feetype')->group('feetype')->select();
        foreach($sjfykm as $k=>$v){
            $v['feetype_name'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
           
            $v['sqje'] = db('cg_ti_list')->where(['ti_id'=> $yw_id,'feetype'=>$v['feetype']])->sum('pizhunhanshui');
           
            $sjfykm[$k] = $v;
        }
        $this->assign('sjfykm',$sjfykm);
        $this->dangnian($info['start'],$info["jxs_id"]);
        return $this->fetch();
    }

    //非常规促销费用申请-待阅
    public function noformalbacklogdetail2(){
        $workId = $this->request->param('workId');
        $trackId = $this->request->param('trackId');
        $myId = $this->request->param('myId');
        //yw_id
        $yw_id =db('cg_workflow')->where('id',$myId)->value('yw_id');
        $this->assign('yw_id',$yw_id);

        if($_POST){
            $type = $this->request->post('type');
            if($type==1){ //选定办理人
                $nodeId = $this->request->post('nodeId');
                $data = $this->request->post('data');
                $selectAuthor = $this->request->post('Author');
                $selectAuthorName = db('users t')->join('employee t2','t.employee_id=t2.id')->where('t.id',$selectAuthor)->value('t2.em_name');
                $data = json_decode($data);
                $data = $this->object_array($data);
                $xdjd = [];
                foreach($data['nextNodes'] as $k=>$v){
                        $v['isSelect'] = "true";
                        $data['nextNodes'][$k] = $v;
                        $xdjd = $v;
                }

                $actionData = [
                    'operate'=>'submit',
                    'operateClazz'=>'com.horizon.wf.action.ActionSubmit',
                    'operateText'=>'提 交',
                    'operateFlag'=>0,
                    'nextNodes'=>[
                        [
                            'nodeKey'=>$xdjd['nodeKey'],
                            'selectId'=>$xdjd['selectId'],
                            'selectName'=>$xdjd['selectName'],
                            'isSelect'=>$xdjd['isSelect'],
                            'authors'=>[
                                'Author'=>[
                                    'authorId'=>'Author',
                                    'selectAuthor'=>$selectAuthor,
                                    'selectAuthorName'=>$selectAuthorName,
                                ]
                            ],
                            'nodeId'=>$data['nextNodes'][0]['nodeId'],
                            'nodeName'=>$data['nextNodes'][0]['nodeName'],
                        ]
                    ],
                    "subFlows"=>null
                ];
                $param = [
                    'accessToken'=>session("accessToken"),
                    'workId'=>$workId,
                    'trackId'=>$trackId,
                    'nodeId'=>$nodeId,
                    'actionData'=>$actionData,
                    "comment"=>"",
                    "dataId"=>"",
                ];
                $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/action.wf',$param);


                if($data['operateMsg']=='提交成功'){
                    $spyj = $this->request->post('spyj');
                    db('cg_workflow_spyj')->insert([
                        'spr_id'=>session('employee_id'),
                        'spr_name'=>db('employee')->where('id',session('employee_id'))->value('em_name'),
                        'spr_job'=>db('job t')->join('job_employee t2','t2.job_id=t.id')->where('t2.employee_id',session('employee_id'))->value('t.job_name'),
                        'wf_id'=>$myId,
                        'spyj'=>$spyj,
                        'spdz'=>$xdjd['nodeName'],
                        'spsj'=>date('Y-m-d H:i:s')
                    ]);

                    //$xdjd['nodeName']或者$data['nextNodes'][0]['nodeName'];
                    db('cg_ti')->where('id',$yw_id)->update(['status'=>$xdjd['nodeName']]);

                    $this->redirect('index');
                }else{
                    echo $data['operateMsg'];
                }
                die;
            }elseif($type==2){ //选定节点
                $data = $this->request->post('data');
                $nodeId = $this->request->post('node');
                $data = json_decode($data);
                $data = $this->object_array($data);
                $spyj = $this->request->post('spyj');
                $this->assign('spyj',$spyj);
                $xdjd = [];
                foreach($data['nextNodes'] as $k=>$v){
                    if($v['nodeId'] == $nodeId){
                        $v['isSelect'] = "true";
                        $data['nextNodes'][$k] = $v;
                        $xdjd = $v;
                    }

                }
                $nodeId = $data['nodeId'];

                $nextNodes = [[
                    'nodeKey'=>$xdjd['nodeKey'],
                    'selectId'=>$xdjd['selectId'],
                    'selectName'=>$xdjd['selectName'],
                    'isSelect'=>$xdjd['isSelect']
                ]];
                $actionData = [
                    'operate'=>'submit',
                    'operateClazz'=>'com.horizon.wf.action.ActionSubmit',
                    'operateText'=>'提 交',
                    'operateFlag'=>1,
                    'nextNodes'=>$nextNodes
                ];
                $param = [
                    'accessToken'=>session("accessToken"),
                    'workId'=>$workId,
                    'trackId'=>$trackId,
                    'nodeId'=>$nodeId,
                    'actionData'=>$actionData,
                ];
                $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/action.wf',$param);

                $data = object_array($data);
                $this->assign('data',$data);
                return $this->fetch('xzblr');
            }else{
                $nodeId = $this->request->post('nodeId');
                $spyj = $this->request->post('spyj');
                $this->assign('spyj',$spyj);
                $actionData = [
                    'operate'=>'submit',
                    'operateClazz'=>'com.horizon.wf.action.ActionSubmit',
                    'operateText'=>'提 交',
                    'operateFlag'=>1,
                ];
                $param = [
                    'accessToken'=>session("accessToken"),
                    'workId'=>$workId,
                    'trackId'=>$trackId,
                    'nodeId'=>$nodeId,
                    'actionData'=>$actionData,
                ];
                $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/action.wf',$param);

                $data = object_array($data);
                $this->assign('data',$data);
                if($data['operateMsg'] == '请从列表中选择节点'){
                    return $this->fetch('xzjd');
                }else{
                    return $this->fetch('xzblr');
                }
            }
            die;
        }
        //打开工作流
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['workId'] = $workId;
        $post_data['trackId'] = $trackId;
        $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$post_data);
        $data = object_array($data);
        $this->assign('data',$data);



        $info = db('cg_ti')->where('id',$yw_id)->find();
        $info['jxs_name'] = db('cg_jxs')->where('id',$info['jxs_id'])->value('title');
        $info['sqr'] = db('employee')->where('id',$info['cuser'])->value('em_name');
        $info['sqr_job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->where('t2.employee_id',$info['cuser'])->value('t.job_name');
        $info['zoning'] = db('cg_market_zoning t')->join('cg_jxs t2','t2.zoning=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['provice'] = db('cg_market_provice t')->join('cg_jxs t2','t2.provice=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['city'] = db('cg_market_city t')->join('cg_jxs t2','t2.city=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['jxs_type'] = db('cg_jxs_types t')->join('cg_jxs t2','t2.types=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['start'] = db('cg_ti_list')->where('ti_id',$yw_id)->value('start');
        $info['end'] = db('cg_ti_list')->where('ti_id',$yw_id)->value('end');

        if($info['productlat']==1){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'brand'=>['exp','is not null']])->value('brand');
            $info['pro_label'] = '品牌';
            $info['pro_name'] = db('pro_brands')->where('id',$brand_id)->value('brand_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->count('brand');
        }elseif($info['productlat']==2){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'category'=>['exp','is not null']])->value('category');
            $info['pro_label'] = '品类';
            $info['pro_name'] = db('pro_category')->where('id',$brand_id)->value('category_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->count('category');
        }elseif($info['productlat']==3){
            $info['pro_label'] = '系列';
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'series'=>['exp','is not null']])->value('series');
            $info['pro_name'] = db('pro_series')->where('id',$brand_id)->value('series_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->count('series');
        }elseif($info['productlat']==4){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'sku'=>['exp','is not null']])->value('sku');
            $info['pro_label'] = 'sku';
            $info['pro_name'] = db('pro_sku')->where('id',$brand_id)->value('sku_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->count('sku');
        }elseif($info['productlat']==5){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'product'=>['exp','is not null']])->value('product');
            $info['pro_label'] = '产品';
            $info['pro_name'] = db('pro_products')->where('id',$brand_id)->value('pro_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->count('product');
        }

        //费用类型
        $info['fylx'] = Db::query('select count(*) cnt from (select feetype from cg_ti_list where ti_id='.$yw_id.' group by feetype) t')[0]['cnt'];
        $info['fylx_name'] = db('cg_ti_list t')->join('cg_feiyongkemu3 t2','t2.id=t.feetype')->where('ti_id',$yw_id)->value('t2.title');
        $info['fye'] = round(db('cg_ti_list')->where(['ti_id'=>$yw_id])->sum('yjsjtrfy'),2);
        $info['xl'] = round(db('cg_ti_list')->where(['ti_id'=>$yw_id])->sum('totalExpectedSales'),2);
        $info['fyl'] = round($info['fye']/$info['xl']*100,2);
        $gs = db('cg_ti_list')->where(['ti_id'=>$yw_id])->count();
        $yujiroi = db('cg_ti_list')->where(['ti_id'=>$yw_id])->sum('yujiroi');
        $info['roi'] = round($yujiroi/$gs,2);

        //查看活动是否重复--判断是否存在费用类型相同收款方也相同的情况
        /*$cnt1 = Db::query('SELECT count(*) cnt from (SELECT gys,count(gys) AS count FROM cg_ti_list where ti_id='.$yw_id.' and gys is not null GROUP BY feetype,payee HAVING count > 1) t');
        $cnt1 = $cnt1[0]['cnt'];

        $info['iscf'] =$cnt1;*/

        $this->assign('info',$info);

        /**
         *问题点--start
         */
        $wtd = [];
        //公司建议的TI活动最高费用率值
        $feiYongLv = db('system_param')->where(['t'=>0,'k'=>'feiYongLv'])->value('v');
        if($info['fyl']>$feiYongLv){
            $wtd[] = '本申请单费用率不符合公司规定，公司规定为：'.$feiYongLv.'%';
        }
        //公司建议的TI活动ROI合格值
        $minRoi = db('system_param')->where(['t'=>0,'k'=>'minRoi'])->value('v');
        if($info['roi']<$minRoi){
            $wtd[] = '本申请单ROI不符合公司规定，公司规定合格值为：'.$minRoi.'%';
        }
        //公司建议的TI活动ROI较优值
        $maxRoi = db('system_param')->where(['t'=>0,'k'=>'maxRoi'])->value('v');
        /**
         *问题点--end
         */

        /**
         * 活动列表--start
         */
        $ti_list = db('cg_ti_list')->where('ti_id',$yw_id)->field('start,end,feetype,product,brand,category,series,sku,yjsjtrfy,totalExpectedSales,paymethod')->select();
        foreach($ti_list as $k=>$v){
            $v['feetype_name'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
            if($v['product'])
                $v['product_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
            elseif($v['brand'])
                $v['product_name'] = db('pro_brands')->where('id',$v['brand'])->value('brand_name');
            elseif($v['category'])
                $v['product_name'] = db('pro_category')->where('id',$v['category'])->value('category_name');
            elseif($v['series'])
                $v['product_name'] = db('pro_series')->where('id',$v['series'])->value('series_name');
            elseif($v['sku'])
                $v['product_name'] = db('pro_sku')->where('id',$v['sku'])->value('sku_name');
            $v['yjfyl'] = round($v['yjsjtrfy']/$v['totalExpectedSales']*100,2);
            $v['zffs'] = db('cg_paymethod')->where('id',$v['paymethod'])->value('title');
            $ti_list[$k] = $v;
        }
        $this->assign('ti_list',$ti_list);
        /**
         * 活动列表--end
         */

        //本次申请已耗时
        $time = time()-$info['ctime'];
        $bcsqhs = $this->vtime($time);
        $this->assign('bcsqhs',$bcsqhs);

        //获取操作记录
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['workId'] = $workId;
        $czjl = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/history.wf',$post_data);
        $czjl = object_array($czjl);
//        echo "<pre>";print_r($czjl);
        foreach($czjl as $k=>$v){
            //查询审批意见
            $wf_id = 0;
//            $v['spyj'] = db('cg_workflow_spyj')->where(['wf_id'=>$wf_id,'spr_id']);
        }
        $this->assign('czjl',$czjl);

        //查询附件
        $attachs = db('cg_workflow_spyj')->where('wf_id',$myId)->column('attach');
        if($attachs){
            $attach = [];
            foreach($attachs as $item){
                if($item){
                    $item = unserialize($item);
                    foreach($item as $k=>$v){
                        $temp = Db::table('annex')->where(array('id'=>$v))->find();
                        $temp['path'] = '/uploads/'.$temp['path'];
                        $item[$k] = $temp;
                    }
                    $attach = array_merge($attach,$item);
                }
            }

            $this->assign('attach',$attach);

        }

        return $this->fetch();
    }

    function vtime($time){
        $output = '';
        foreach (array(86400 => '天', 3600 => '小时', 60 => '分', 1 => '秒') as $key => $value) {
            if ($time >= $key) $output .= floor($time/$key) . $value;
            $time %= $key;
        }
        return $output;
    }
    //ti进场实际
    public function tijinchangview(){
                $id = $this->request->param('id');
        $data = db('cg_ti')->where('id',$id)->find();
        if(!$data){
            return '参数错误';
        }
        $data['zoning'] = db('cg_jxs t')->join('cg_market_zoning t2','t2.id=t.zoning')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['provice'] = db('cg_jxs t')->join('cg_market_provice t2','t2.id=t.provice')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['city'] = db('cg_jxs t')->join('cg_market_city t2','t2.id=t.city')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['cusername'] = db('employee')->where('id',$data['cuser'])->value('em_name');

        switch ($data['status']){
            case 2:
                $data['status_title'] = '已打回';
                break;
            case 3:
                $data['status_title'] = '区域领导审批';
                break;
            case 4:
                $data['status_title'] = '拆分人审批';
                break;
            case 5:
                $data['status_title'] = '集团领导审批';
                break;
            case 6:
                $data['status_title'] = '抄送';
                break;
            case 7:
                $data['status_title'] = '已归档';
                break;
            case 8:
                $data['status_title'] = '已作废';
                break;
            case 9:
                $data['status_title'] = '已否决';
                break;
            default:
                $data['status_title'] = '草稿';
        }
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        //经销商性质-直营
        $data['direct'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('direct');
//        申请人职位
        $data['job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->join('employee t3','t3.id=t2.employee_id')->where('t3.id',$data['cuser'])->value('t.job_name');
        //申请人部门
        $data['sjrbm'] = db('department_employee t')
            ->join('department t2','t2.id=t.department_id')
            ->where(['t.index'=>1,'employee_id'=>$data['cuser']])
            ->value('t2.de_name');

        //查询明细列表
        $list = db('cg_ti_list')->where('ti_id',$id)->group('net_id')->field('net_id')->select();
        $wds = count($list); //网点数
        $this->assign('wds',$wds);
        foreach($list as $k=>$v){
            $v['_child'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->select();
            $v['st_amount'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('amount');//小计-未税费用金额
            $v['st_hanshui'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('hanshui');//小计-含税费用金额
            $v['st_shijitourufeiyong'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('fb_shijitourufeiyong');//小计-实际投入费用

            $list[$k] = $v;
        }
        $zj_weishui = 0;
        $zj_hanshui = 0;
        $zj_shijitouru = 0;
        foreach($list as $k=>$v){
            $xj_weishui = 0;
            $xj_hanshui = 0;
            $xj_shijitouru = 0;
            foreach($v['_child'] as $k1=>$v1){

                $v1['system_title'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v1['net_id'])->value('t.title');
                $v1['net_title'] = db('cg_net')->where('id',$v1['net_id'])->value('title');
                $system_id = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v1['net_id'])->value('t.id');
                $v1['system_net_num'] = db('cg_net')->where('system_id',$system_id)->count();
                $v1['net_addr'] = db('cg_net')->where('id',$v1['net_id'])->value('detailAddress');
                $v1['net_cat'] = db('cg_net t')->join('cg_networktype t2','t2.id=t.cat')->where('t.id',$v1['net_id'])->value('t2.title');
                $v1['product_series'] = db('pro_series t')->join('pro_sku t2','t2.series_id=t.id')->join('pro_products t3','t3.sku_id=t2.id')->where('t3.id',$v1['f1'])->value('t.series_name');
                $sid = db('pro_series t')->join('pro_sku t2','t2.series_id=t.id')->join('pro_products t3','t3.sku_id=t2.id')->where('t3.id',$v1['f1'])->value('t.id');
                $c = db('pro_category t')->join('pro_series t2','t2.category_id=t.id')->where('t2.id',$sid)->value('t.category_name');
                $b = db('pro_brands t3')->join('pro_category t','t3.id=t.brand_id')->join('pro_series t2','t2.category_id=t.id')->where('t2.id',$sid)->value('t3.brand_name');
                $v1['product_series'] = $b.'-'.$c.'-'.$v1['product_series'];
                $v1['unit'] = db('pro_products')->where('id',$v1['f1'])->value('unit');
                $v1['jiajialv1'] = round(($v1['f3']-$v1['f2'])/($v1['f2']?$v1['f2']:1)*100,2);
                $v1['jiajialv2'] = round(($v1['f4']-$v1['f2'])/($v1['f2']?$v1['f2']:1)*100,2);
                $v1['jiajialv3'] = round(($v1['f5']-$v1['f2'])/($v1['f2']?$v1['f2']:1)*100,2);
                $v1['feetype'] = db('cg_feiyongkemu3')->where('id',$v1['feetype'])->value('title');
                $v1['paymethod'] = db('cg_paymethod')->where('id',$v1['paymethod'])->value('title');
                $v1['isVAT'] = $v1['isVAT']==1?'是':'否';
                $v1['jrbm'] = db('department')->where('id',$v1['jrbm'])->value('de_name');
                $v1['project'] = db('cg_fijiru')->where('id',$v1['project'])->value('title');
                $xj_weishui += $v1['amount'];
                $xj_hanshui += $v1['hanshui'];
                $xj_shijitouru += $v1['fb_shijitourufeiyong'];
                $v['_child'][$k1] = $v1;
            }
            $v['system_title'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v['net_id'])->value('t.title');
            $v['net_title'] = db('cg_net')->where('id',$v['net_id'])->value('title');
            $system_id = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v['net_id'])->value('t.id');
            $v['system_nets'] = db('cg_net')->where('system_id',$system_id)->count(); //系统网点数
            $v['net_addr'] = db('cg_net')->where('id',$v['net_id'])->value('detailAddress'); //网点详细地址
            $v['net_cat'] = db('cg_networktype t')->join('cg_net t2','t2.cat=t.id')->where('t2.id',$v['net_id'])->value('t.title'); //网点类型
            $net_yjc = db('cg_net_barcode t')->join('pro_products t2','t2.id=t.prod')->where('t.net_id',$v['net_id'])->column('pro_name');
            $net_yjc = array_unique($net_yjc);
            $net_yjc = implode('</option><option>',$net_yjc);
            $v['net_yjc'] = "<select style='height:50px;' multiple readonly><option>{$net_yjc}</option></select>";

            //小计-未税费用金额
            $v['xj_weishui'] = $xj_weishui;
            $v['xj_hanshui'] = $xj_hanshui;
            $v['xj_shijitouru'] = $xj_shijitouru;
            $list[$k] = $v;
            $zj_weishui += $xj_weishui;
            $zj_hanshui += $xj_hanshui;
            $zj_shijitouru += $xj_shijitouru;
            $list[$k] = $v;
        }

        $data['list'] = $list;
//        echo db('cg_ti_list')->getLastSql();
        $this->assign('data',$data);
        $this->assign('zj_weishui',$zj_weishui);
        $this->assign('zj_hanshui',$zj_hanshui);
        $this->assign('zj_shijitouru',$zj_shijitouru);
        $feiarr=Db("cg_ti_list")->where(["ti_id"=>$id])->group("feetype")->field("feetype,sum(fb_shijitourufeiyong) as feiyong")->select();
        for($i=0;$i<count($feiarr);$i++){
            $feiarr[$i]["title"]=db("cg_feiyongkemu3")->where(["id"=>$feiarr[$i]["feetype"]])->value("title");
        }
        $this->assign("feiarr",$feiarr);
        $logs=$this->getlog(1,$id);
        $this->assign("logs",$logs);
        return $this->fetch();
    }
    //ti进场决策宝
    public function tijinchang(){
        $workId = $this->request->param('workId');
        $trackId = $this->request->param('trackId');
        $myId = $this->request->param('myId');
//yw_id
        $yw_id =db('cg_workflow')->where('id',$myId)->value('yw_id');

        $this->assign('yw_id',$yw_id);
        $state=db("cg_ti")->where(["id"=>$yw_id])->value("status");
        if($state==2){
             //打回
            $this->redirect('Tijinchang/update', ['id' => $yw_id,"from"=>2]);
            return;
        }
         //打开工作流
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['workId'] = $workId;
        $post_data['trackId'] = $trackId;
        $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$post_data);
        $data = object_array($data);
        $this->assign('data',$data);
    
        $info = db('cg_ti')->where('id',$yw_id)->find();
        $info['jxs_name'] = db('cg_jxs')->where('id',$info['jxs_id'])->value('title');
        $info['sqr'] = db('employee')->where('id',$info['cuser'])->value('em_name');
        $info['sqr_job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->where('t2.employee_id',$info['cuser'])->value('t.job_name');
        $info['zoning'] = db('cg_market_zoning t')->join('cg_jxs t2','t2.zoning=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['provice'] = db('cg_market_provice t')->join('cg_jxs t2','t2.provice=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['city'] = db('cg_market_city t')->join('cg_jxs t2','t2.city=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['jxs_type'] = db('cg_jxs_types t')->join('cg_jxs t2','t2.types=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info["year"]=db('cg_ti_list')->where(['ti_id'=>$yw_id])->value('year');
        $info["month"]=db('cg_ti_list')->where(['ti_id'=>$yw_id])->value('month');
        $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'f1'=>['exp','is not null']])->value('f1');
            $info['pro_label'] = '产品';
            $info['pro_name'] = db('pro_products')->where('id',$brand_id)->value('pro_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->group("f1")->count('f1');

        $net_num = Db::table("cg_ti_list")->where(["ti_id"=>$yw_id])->group("net_id")->count();
        $this->assign("net_num", $net_num);
        $info["net"]=Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")->where(["ap.id" => $yw_id])->value("n.title");
        $info["nettype"]=Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")->join("cg_networktype cn","n.cat=cn.id")->where(["ap.id" => $yw_id])->value("cn.title");

        $time = time()-$info['ctime'];
        $bcsqhs = $this->vtime($time);
        $this->assign('bcsqhs',$bcsqhs);

        //获取操作记录
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['workId'] = $workId;
        $czjl = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/history.wf',$post_data);
        $czjl = object_array($czjl);
//        echo "<pre>";print_r($czjl);
        foreach($czjl as $k=>$v){
            //查询审批意见
            $wf_id = 0;
//            $v['spyj'] = db('cg_workflow_spyj')->where(['wf_id'=>$wf_id,'spr_id']);
        }
        $this->assign('czjl',$czjl);
         //费用类型
        $info['fylx'] = Db::query('select count(*) cnt from (select feetype from cg_ti_list where ti_id='.$yw_id.' group by feetype) t')[0]['cnt'];
        $info['fylx_name'] = db('cg_ti_list t')->join('cg_feiyongkemu3 t2','t2.id=t.feetype')->where('ti_id',$yw_id)->value('t2.title');


         //按照三级费用科目查询
        $sjfykm = db('cg_ti_list')->where('ti_id', $yw_id)->field('feetype')->group('feetype')->select();
        $heji["hanshui"]=0;
        foreach($sjfykm as $k=>$v){
            $v['feetype_name'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
           
            $v['sqje'] = db('cg_ti_list')->where(['ti_id'=> $yw_id,'feetype'=>$v['feetype']])->sum('yjsjtrfy');
           $heji["hanshui"]+=$v['sqje'];
            $sjfykm[$k] = $v;
        }
        $heji["hanshui"]=round($heji["hanshui"],2);
        $this->assign("heji",$heji);
        $this->assign('sjfykm',$sjfykm);
        $applyde=db("cg_ti_list")->where('ti_id', $yw_id)->select();
         $yusuan=Db::table("yusuan_detail")->alias("yd")->join("yusuan y","yd.yid=y.id")
        ->where(["yd.aid"=>$yw_id,"y.type"=>1])->group("yd.did")->field("yd.aid,yd.did,sum(yd.jine) as jine,sum(yd.tianshu) as tianshu,max(yd.zongtianshu) as zongtianshu")
        ->select();
        $checkwt["ys"]=0;$wtd=[];
        $flag1=0;//是否所有明细都有匹配预算
       
        if(count($applyde)>count($yusuan)){
           $flag1=1;
        }
        $flag2=0;//超出预算情况
        $yusuande=Db::table("yusuan_detail")->alias("yd")->join("yusuan y","yd.yid=y.id")
        ->where(["yd.aid"=>$yw_id,"y.type"=>1])->group("y.id")->field("y.id,y.jine,sum(yd.jine) as sjine,y.yijikaoheqi,y.erjikaoheqi,y.cainian,y.channel1,y.pinpai,y.erjifeiyong")->select();
         //预算明细处理
        if($flag1==1){
            $checkwt["ys"]=1;//未设定预算
            $wtd[] ="本申请中存在未设定预算的明细";
        }
        for($i=0;$i<count($yusuande);$i++){
            //已通过预算的使用金额
           $yusuande[$i]["ytongguo"]=round(Db::table("yusuan_detail")->where(["yid"=>$yusuande[$i]["id"],"type"=>2])->sum("jine"),2);
           if(!$yusuande[$i]["ytongguo"])
                $yusuande[$i]["ytongguo"]=0;
           //申请中的预算使用金额
           $yusuande[$i]["shenqingzhong"]=round(Db::table("yusuan_detail")->where(["yid"=>$yusuande[$i]["id"],"type"=>1])->sum("jine"),2);
           if(!$yusuande[$i]["shenqingzhong"])
                $yusuande[$i]["shenqingzhong"]=0;
           if($yusuande[$i]["ytongguo"]>=$yusuande[$i]["jine"]){
                $yusuande[$i]["deng"]=2;
                $flag2=2;
           }else if($yusuande[$i]["ytongguo"]+$yusuande[$i]["shenqingzhong"]>$yusuande[$i]["jine"]){
                $yusuande[$i]["deng"]=1;
                if($flag2<2)
                    $flag2=1;
           }else{
                $yusuande[$i]["deng"]=0;
           }
            
            $yusuande[$i]["cainian"]=Db::table("cg_cainian")->where(["id"=>$yusuande[$i]["cainian"]])->value("title");
            if($yusuande[$i]["erjikaoheqi"]){
                
                $yusuande[$i]["kaoheqi"]=Db::table("cg_kaoheqi2")->where(["id"=>$yusuande[$i]["erjikaoheqi"]])->value("title");
            }else{
               
                $yusuande[$i]["kaoheqi"]=Db::table("cg_kaoheqi1")->where(["id"=>$yusuande[$i]["yijikaoheqi"]])->value("title");
            }
            $yusuande[$i]["channel"]=Db::table("cg_channel_types1")->where(["id"=>$yusuande[$i]["channel1"]])->value("title");
            $yusuande[$i]["pinpai"]=Db::table("pro_brands")->where(["id"=>$yusuande[$i]["pinpai"]])->value("brand_name");
            $yusuande[$i]["erjifeiyong"]=Db::table("cg_feiyongkemu2")->where(["id"=>$yusuande[$i]["erjifeiyong"]])->value("title");
            $yusuande[$i]["weiyong"]=round($yusuande[$i]["jine"]-$yusuande[$i]["ytongguo"],2);
            $yusuande[$i]["sjine"]=round($yusuande[$i]["sjine"],2);
        }
        if($flag2==1){
            $checkwt["ys"]=2;//未设定预算
            $wtd[] ="本申请中存在预算申请将超预算的情况";
        }else if($flag2==2){
            $checkwt["ys"]=3;//未设定预算
            $wtd[] ="本申请中存在预算申请已超预算的情况";
        }
        $this->assign("yusuande",$yusuande);$this->assign("wtd",$wtd);$this->assign("checkwt",$checkwt);
        $this->assign("info",$info);
         $this->dangnian($info['ctime'],$info["jxs_id"]);
        $pro=db("cg_ti_list")->where('ti_id', $yw_id)->group("f1,feetype")
        ->field("f1_title,year,month,count(net_id) as netnum,feetype,sum(yjsjtrfy) as feiyong")->select();
        foreach ($pro as $k => $v) {
            # code...
            
            $kemu3=db("cg_feiyongkemu3")->where(["id"=>$v['feetype']])->find();
            $pro[$k]["kemu3"]=$kemu3["title"];
            $pro[$k]["kemu2"]=db("cg_feiyongkemu2")->where(["id"=>$kemu3["pid"]])->value("title");
        }
        $this->assign("pro",$pro);
        return $this->fetch();
    }
   /* public function formalbacklogdetail(){
         $workId = $this->request->param('workId');
        $trackId = $this->request->param('trackId');
        $myId = $this->request->param('myId');
        //echo 1;exit;
        $this->redirect('Workflowdb/formalbacklogdetail', ['workId' => $workId,'trackId' => $trackId,'myId' => $myId]);
    }*/
    //常规促销费用申请
    public function formalbacklogdetail(){
        $workId = $this->request->param('workId');
        $trackId = $this->request->param('trackId');
        $myId = $this->request->param('myId');
//yw_id
        $yw_id =db('cg_workflow')->where('id',$myId)->value('yw_id');

        $this->assign('yw_id',$yw_id);
        $state=db("cg_ti")->where(["id"=>$yw_id])->value("status");
        if($state==2){
             //打回
            $this->redirect('TiApply/addform', ['aid' => $yw_id,"from"=>2]);
            return;
        }
        //打开工作流
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['workId'] = $workId;
        $post_data['trackId'] = $trackId;
        $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$post_data);
        $data = object_array($data);
        $this->assign('data',$data);
    
        $info = db('cg_ti')->where('id',$yw_id)->find();
        $info['jxs_name'] = db('cg_jxs')->where('id',$info['jxs_id'])->value('title');
        $info['sqr'] = db('employee')->where('id',$info['cuser'])->value('em_name');
        $info['sqr_job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->where('t2.employee_id',$info['cuser'])->value('t.job_name');
        $info['zoning'] = db('cg_market_zoning t')->join('cg_jxs t2','t2.zoning=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['provice'] = db('cg_market_provice t')->join('cg_jxs t2','t2.provice=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['city'] = db('cg_market_city t')->join('cg_jxs t2','t2.city=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['jxs_type'] = db('cg_jxs_types t')->join('cg_jxs t2','t2.types=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['start'] = db('cg_ti_list')->where('ti_id',$yw_id)->value('start');
        $info['end'] = db('cg_ti_list')->where('ti_id',$yw_id)->value('end');
        $info['is_bu'] = db('cg_ti_list')->where('ti_id',$yw_id)->value('is_bu');
        if($info['productlat']==1){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'brand'=>['exp','is not null']])->value('brand');
            $info['pro_label'] = '品牌';
            $info['pro_name'] = db('pro_brands')->where('id',$brand_id)->value('brand_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->group("brand")->count('brand');
        }elseif($info['productlat']==2){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'category'=>['exp','is not null']])->value('category');
            $info['pro_label'] = '品类';
            $info['pro_name'] = db('pro_category')->where('id',$brand_id)->value('category_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->group("category")->count('category');
        }elseif($info['productlat']==3){
            $info['pro_label'] = '系列';
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'series'=>['exp','is not null']])->value('series');
            $info['pro_name'] = db('pro_series')->where('id',$brand_id)->value('series_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->group("series")->count('series');
        }elseif($info['productlat']==4){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'sku'=>['exp','is not null']])->value('sku');
            $info['pro_label'] = 'sku';
            $info['pro_name'] = db('pro_sku')->where('id',$brand_id)->value('sku_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->group("sku")->count('sku');
        }elseif($info['productlat']==5){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'product'=>['exp','is not null']])->value('product');
            $info['pro_label'] = '产品';
            $info['pro_name'] = db('pro_products')->where('id',$brand_id)->value('pro_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->group("product")->count('product');
        }



        $apply=Db::table("cg_ti")->where(["id"=>$yw_id])->find();
        $net_num = Db::table("cg_ti_list")->where(["ti_id"=>$yw_id])->group("net_id")->count();
        $this->assign("net_num", $net_num);
        $system_num=Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")
            ->join("cg_system s", "n.system_id=s.id", "LEFT")->where(["ap.id" => $yw_id])->group("s.id")->count();
            $this->assign("system_num",$system_num);
       $applyde=Db::table("cg_ti_list")->where(["ti_id"=>$yw_id])->select();
       $info["xitong"]=Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")
            ->join("cg_system s", "n.system_id=s.id", "LEFT")->where(["ap.id" => $yw_id])->value("s.title");
     
        $info["xitongtype"]=Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")
            ->join("cg_system s", "n.system_id=s.id", "LEFT")->join("cg_customertype t","s.cusType=t.id")->where(["ap.id" => $yw_id])->value("t.title");
        $info["net"]=Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")->where(["ap.id" => $yw_id])->value("n.title");
        $info["nettype"]=Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")->join("cg_networktype cn","n.cat=cn.id")->where(["ap.id" => $yw_id])->value("cn.title");
        //查看活动是否重复--判断是否存在费用类型相同收款方也相同的情况
        /*$cnt1 = Db::query('SELECT count(*) cnt from (SELECT gys,count(gys) AS count FROM cg_ti_list where ti_id='.$yw_id.' and gys is not null GROUP BY feetype,payee HAVING count > 1) t');
        $cnt1 = $cnt1[0]['cnt'];

        $info['iscf'] =$cnt1;*/

        $this->assign('info',$info);

        

        /**
         * 活动列表--start
         */
        /*$ti_list = db('cg_ti_list')->where('ti_id',$yw_id)->field('start,end,feetype,product,brand,category,series,sku,yjsjtrfy,totalExpectedSales,paymethod')->select();
        foreach($ti_list as $k=>$v){
            $v['feetype_name'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
            if($v['product'])
                $v['product_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
            elseif($v['brand'])
                $v['product_name'] = db('pro_brands')->where('id',$v['brand'])->value('brand_name');
            elseif($v['category'])
                $v['product_name'] = db('pro_category')->where('id',$v['category'])->value('category_name');
            elseif($v['series'])
                $v['product_name'] = db('pro_series')->where('id',$v['series'])->value('series_name');
            elseif($v['sku'])
                $v['product_name'] = db('pro_sku')->where('id',$v['sku'])->value('sku_name');
            $v['yjfyl'] = round($v['yjsjtrfy']/$v['totalExpectedSales']*100,2);
            $v['zffs'] = db('cg_paymethod')->where('id',$v['paymethod'])->value('title');
            $ti_list[$k] = $v;
        }
        $this->assign('ti_list',$ti_list);*/
        /**
         * 活动列表--end
         */

        //本次申请已耗时
        $time = time()-$info['ctime'];
        $bcsqhs = $this->vtime($time);
        $this->assign('bcsqhs',$bcsqhs);

        //获取操作记录
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['workId'] = $workId;
        $czjl = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/history.wf',$post_data);
        $czjl = object_array($czjl);
//        echo "<pre>";print_r($czjl);
        foreach($czjl as $k=>$v){
            //查询审批意见
            $wf_id = 0;
//            $v['spyj'] = db('cg_workflow_spyj')->where(['wf_id'=>$wf_id,'spr_id']);
        }
        $this->assign('czjl',$czjl);

        //查询附件
        $attachs = db('cg_workflow_spyj')->where('wf_id',$myId)->column('attach');
        if($attachs){
            $attach = [];
            foreach($attachs as $item){
                if($item){
                    $item = unserialize($item);
                    foreach($item as $k=>$v){
                        $temp = Db::table('annex')->where(array('id'=>$v))->find();
                        $temp['path'] = '/uploads/'.$temp['path'];
                        $item[$k] = $temp;
                    }
                    $attach = array_merge($attach,$item);
                }
            }

            $this->assign('attach',$attach);

        }
       $prolist= Db::table("cg_ti")->alias("ap")
        ->join("cg_ti_list apd", "apd.ti_id=ap.id")
        ->join("pro_products p", "apd.product=p.id")
        ->join("pro_sku sk", "p.sku_id=sk.id")
        ->join("pro_series ps", "sk.series_id=ps.id")
        ->join("pro_category pc","ps.category_id=pc.id")
        ->join("pro_brands pb","pc.brand_id=pb.id")->where(["ap.id" => $yw_id])->group("apd.product")
        ->field("pro_name,sku_name,brand_name,p.box_num,sum(apd.boxnum) as xiaoliang,sum(apd.totalExpectedSales) as xiaoshoue,sum(apd.totalBenchmarkSales) as jizhun,sum(hanshui) as hanshuis,pb.profit,apd.product,sum(yjsjtrfy) as pizhunhanshuis")->select();
        $heji["xiaoliang"]=0;$heji["xiaoshoue"]=0;$heji["jizhun"]=0;$heji["hanshuis"]=0;$heji["pizhunhanshuis"]=0;
        for($i=0;$i<count($prolist);$i++){
            $heji["xiaoliang"]+=$prolist[$i]["xiaoliang"];
            $heji["xiaoshoue"]+=$prolist[$i]["xiaoshoue"];
            $heji["jizhun"]+=$prolist[$i]["jizhun"];
            $heji["hanshuis"]+=$prolist[$i]["hanshuis"];$heji["pizhunhanshuis"]+=$prolist[$i]["pizhunhanshuis"];
            $prolist[$i]["feiyonglv"]=$prolist[$i]["hanshuis"]/$prolist[$i]["xiaoshoue"]*100;
            $prolist[$i]["roi"]=($prolist[$i]["xiaoshoue"]-$prolist[$i]["jizhun"])*$prolist[$i]["profit"]/$prolist[$i]["hanshuis"]/100;
            $prolist[$i]["feec"]=Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")->where(["ap.id" => $yw_id,"apd.product"=>$prolist[$i]["product"]])
            ->group("f3.id")->count();
            $prolist[$i]["fee"]=Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")->join("cg_feiyongkemu3 k3", "apd.feetype=k3.id")
            ->join("cg_feiyongkemu2 k2","k3.pid=k2.id")->where(["ap.id" => $yw_id,"apd.product"=>$prolist[$i]["product"]])
            ->group("k3.id")->field("k3.title as kemu3,k2.title as kemu2,sum(hanshui) as hanshuis")->select();
            

        }

        $this->assign("heji",$heji);
        $this->assign("prolist",$prolist);

        //费用类型
        $info['fylx'] = Db::query('select count(*) cnt from (select feetype from cg_ti_list where ti_id='.$yw_id.' group by feetype) t')[0]['cnt'];
        $info['fylx_name'] = db('cg_ti_list t')->join('cg_feiyongkemu3 t2','t2.id=t.feetype')->where('ti_id',$yw_id)->value('t2.title');
        $info['fye'] = $heji["pizhunhanshuis"];
        $info['xl'] = $heji["xiaoshoue"];

        $info['fyl'] = round($info['fye']/$info['xl']*100,2);
        $gs = db('cg_ti_list')->where(['ti_id'=>$yw_id])->count();
        $yujiroi = db('cg_ti_list')->where(['ti_id'=>$yw_id])->sum('yujiroi*yjsjtrfy');
        if($heji["pizhunhanshuis"])
            $info['roi'] = round($yujiroi/$heji["pizhunhanshuis"],2);
        else
            $info['roi'] = 0;
        /**
         *问题点--start
         */
        $wtd = [];$checkwt["fyl"]=0;$checkwt["roi"]=0;$checkwt["fanwei"]=0;$checkwt["ys"]=0;
        //公司建议的TI活动最高费用率值
        $feiYongLv = db('system_param')->where(['t'=>0,'k'=>'feiYongLv'])->value('v');
        if($info['fyl']>$feiYongLv){
            $checkwt["fyl"]=1;
            $wtd[] = '本申请单费用率不符合公司规定，公司规定为：'.$feiYongLv.'%';
        }
        //公司建议的TI活动ROI合格值
        $minRoi = db('system_param')->where(['t'=>0,'k'=>'minRoi'])->value('v');
        if($info['roi']<$minRoi){
            $wtd[] = '本申请单ROI低于公司规定，公司规定最小值为：'.$minRoi.'%';
            $checkwt["roi"]=1;
        }
        //公司建议的TI活动ROI较优值
        $maxRoi = db('system_param')->where(['t'=>0,'k'=>'maxRoi'])->value('v');
        if($info['roi']>$maxRoi){
            $wtd[] = '本申请单ROI高于公司规定，公司规定最大值为：'.$maxRoi.'%';
            $checkwt["roi"]=2;
        }
        //未设定完全价格体系的产品是否存在
        $nop=db("cg_ti_list")->alias("apd")->join("pro_products p", "apd.product=p.id")->join("pro_price pp","pp.pid=p.id")
        ->where("(pp.retail_low is null or pp.retail_low=0 or retail_high=0 or retail_high is null or pp.promotion_high is null or pp.promotion_high=0 or promotion_low is null or promotion_low=0) and apd.ti_id={$yw_id}")
        ->group("apd.product")->field("p.pro_name,apd.wangdian_price,pp.retail_low,pp.retail_high,pp.promotion_high,pp.promotion_low")->select();
        //print_r($nop);
        if($nop){
            $checkwt["fanwei"]=1;
            for($i=0;$i<count($nop);$i++){
                $wtd[] ="本申请中产品:{$nop[$i]["pro_name"]} 的定价体系未设定完全";
            }
        }
        //网点定价不在合法范围内
        $netout=db("cg_ti_list")->alias("apd")->join("pro_products p", "apd.product=p.id")->join("pro_price pp","pp.pid=p.id")->where(["netout"=>1,"ti_id" => $yw_id])
        ->group("p.id")->field("p.pro_name,apd.wangdian_price,pp.retail_low,pp.retail_high")->select();
        if($netout){
            $checkwt["fanwei"]=2;
            for($i=0;$i<count($netout);$i++){
                $wtd[] ="本申请中产品:{$netout[$i]["pro_name"]} 的网点供货价不符合公司规定的范围({$netout[$i]["retail_low"]}~{$netout[$i]["retail_high"]})";
            }
        }
        //活动零售价不再合法范围内
        $huodongout=db("cg_ti_list")->alias("apd")->join("pro_products p", "apd.product=p.id")->join("pro_price pp","pp.pid=p.id")->where(["huodongout"=>1,"ti_id" => $yw_id])
        ->group("p.id")->field("p.pro_name,apd.huodong_price,pp.promotion_high,pp.promotion_low")->select();
        if($huodongout){
            $checkwt["fanwei"]=2;
            for($i=0;$i<count($huodongout);$i++){
                $wtd[] ="本申请中产品:{$huodongout[$i]["pro_name"]} 的促销活动价不符合公司规定的范围({$huodongout[$i]["promotion_low"]}~{$huodongout[$i]["promotion_high"]})";
            }
        }
        //运算按照明细合并
        $yusuan=Db::table("yusuan_detail")->alias("yd")->join("yusuan y","yd.yid=y.id")
        ->where(["yd.aid"=>$yw_id,"y.type"=>1])->group("yd.did")->field("yd.aid,yd.did,sum(yd.jine) as jine,sum(yd.tianshu) as tianshu,max(yd.zongtianshu) as zongtianshu")
        ->select();
       // print_r($yusuan);
        $flag1=0;//是否所有明细都有匹配预算
       
        if(count($applyde)>count($yusuan)){
            //echo 1;
           $flag1=1;
        }
        
        for($i=0;$i<count($yusuan);$i++){
            if($yusuan[$i]["tianshu"]<$yusuan[$i]["zongtianshu"]){
                //echo 2;
                $flag1=1;
            }
        }
        //echo $flag1;
        if($flag1==1){
            $checkwt["ys"]=1;//未设定预算
            $wtd[] ="本申请中存在未设定预算的明细";
        }
        $flag2=0;//超出预算情况
        $yusuande=Db::table("yusuan_detail")->alias("yd")->join("yusuan y","yd.yid=y.id")
        ->where(["yd.aid"=>$yw_id,"y.type"=>1])->group("y.id")->field("y.id,y.jine,sum(yd.jine) as sjine,y.yijikaoheqi,y.erjikaoheqi,y.cainian,y.channel1,y.pinpai,y.erjifeiyong")->select();
         //预算明细处理

        for($i=0;$i<count($yusuande);$i++){
            //已通过预算的使用金额
           $yusuande[$i]["ytongguo"]=round(Db::table("yusuan_detail")->where(["yid"=>$yusuande[$i]["id"],"type"=>2])->sum("jine"),2);
           if(!$yusuande[$i]["ytongguo"])
                $yusuande[$i]["ytongguo"]=0;
           //申请中的预算使用金额
           $yusuande[$i]["shenqingzhong"]=round(Db::table("yusuan_detail")->where(["yid"=>$yusuande[$i]["id"],"type"=>1])->sum("jine"),2);
           if(!$yusuande[$i]["shenqingzhong"])
                $yusuande[$i]["shenqingzhong"]=0;
           if($yusuande[$i]["ytongguo"]>=$yusuande[$i]["jine"]){
                $yusuande[$i]["deng"]=2;
                $flag2=2;
           }else if($yusuande[$i]["ytongguo"]+$yusuande[$i]["shenqingzhong"]>$yusuande[$i]["jine"]){
                $yusuande[$i]["deng"]=1;
                if($flag2<2)
                    $flag2=1;
           }else{
                $yusuande[$i]["deng"]=0;
           }
            
            $yusuande[$i]["cainian"]=Db::table("cg_cainian")->where(["id"=>$yusuande[$i]["cainian"]])->value("title");
            if($yusuande[$i]["erjikaoheqi"]){
                
                $yusuande[$i]["kaoheqi"]=Db::table("cg_kaoheqi2")->where(["id"=>$yusuande[$i]["erjikaoheqi"]])->value("title");
            }else{
               
                $yusuande[$i]["kaoheqi"]=Db::table("cg_kaoheqi1")->where(["id"=>$yusuande[$i]["yijikaoheqi"]])->value("title");
            }
            $yusuande[$i]["channel"]=Db::table("cg_channel_types1")->where(["id"=>$yusuande[$i]["channel1"]])->value("title");
            $yusuande[$i]["pinpai"]=Db::table("pro_brands")->where(["id"=>$yusuande[$i]["pinpai"]])->value("brand_name");
            $yusuande[$i]["erjifeiyong"]=Db::table("cg_feiyongkemu2")->where(["id"=>$yusuande[$i]["erjifeiyong"]])->value("title");
            $yusuande[$i]["weiyong"]=round($yusuande[$i]["jine"]-$yusuande[$i]["ytongguo"],2);
            $yusuande[$i]["sjine"]=round($yusuande[$i]["sjine"],2);
        }
        if($flag2==1){
            $checkwt["ys"]=2;//未设定预算
            $wtd[] ="本申请中存在预算申请将超预算的情况";
        }else if($flag2==2){
            $checkwt["ys"]=3;//未设定预算
            $wtd[] ="本申请中存在预算申请已超预算的情况";
        }
        $this->assign("yusuande",$yusuande);
        //按照三级费用科目查询
        $sjfykm = db('cg_ti_list')->where('ti_id', $yw_id)->field('feetype')->group('feetype')->select();
        foreach($sjfykm as $k=>$v){
            $v['feetype_name'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
           
            $v['sqje'] = db('cg_ti_list')->where(['ti_id'=> $yw_id,'feetype'=>$v['feetype']])->sum('pizhunhanshui');
           
            $sjfykm[$k] = $v;
        }
        $this->assign('sjfykm',$sjfykm);
        /**
         *问题点--end
         */
        $this->assign("checkwt",$checkwt);
        $this->assign("wtd",$wtd);
        $this->assign("info",$info);
        /*当年*/

        $this->dangnian($info['start'],$apply["jxs_id"]);
        return $this->fetch();
    }
    // new TPM专项
    public function newfreeapply(){
        $workId = $this->request->param('workId');
        $trackId = $this->request->param('trackId');
        $myId = $this->request->param('myId');
        $yw_id =db('cg_workflow')->where('id',$myId)->value('yw_id');
        $this->assign('yw_id',$yw_id);
        $state=db("cg_ti")->where(["id"=>$yw_id])->value("status");

        $aid=$yw_id;
        $apply = Db::table("cg_ti")->alias("ap")
            ->join("cg_jxs j", "ap.jxs_id=j.id")
            ->where(["ap.id" => $aid])->field("ap.id,ap.sfxyfk,ap.sn,ap.jxs_id,ap.is_notice,ap.brief as remark,ap.title,j.title as jxs,ap.attach as annex_id,status,is_jinhuo,jinhuo_jine,jinhuo_shijian_start,jinhuo_shijian_end")
            ->find();
        $apply['jinhuo_shijian_start']=date('Y-m-d',$apply['jinhuo_shijian_start']);
        $apply['jinhuo_shijian_end']=date('Y-m-d',$apply['jinhuo_shijian_end']);
        $this->assign("apply", $apply);
        if ($apply["annex_id"])
            $fujian = Db::table("annex")->where("id in({$apply["annex_id"]})")->select();
        $logs=$this->getlog(24,$aid);
        foreach ($logs as $k => $v) {
            # code...
            $uid=$v["USERID"];
            $eid=db("users")->where(["id"=>$uid])->value("employee_id");
            $logs[$k]["depart"]=db("department_employee de")->join("department d","de.department_id=d.id")->where(["de.employee_id"=>$eid,"de.index"=>1])->value("d.de_name");
            $logs[$k]["job"]=db("job_employee je")->join("job j","je.job_id=j.id")->where(["je.employee_id"=>$eid])->value("j.job_name");
        }
        $this->assign("logs",$logs);
        //print_r($logs);exit;
        $xxxx=Db::name('cg_ti_list')->where(['ti_id'=>$aid])->field('*')->select();//详细信息
        $xxxxnum=count($xxxx);

        foreach ($xxxx as $k2=>&$v2){
            if($xxxxnum!=0){
                $v2['hdxl']=round($v2['yesSales']/$xxxxnum,2);
            }else{
                $v2['hdxl']=$v2['yesSales'];
            }
            if(!empty($v2['hdxl'])){
                $v2['yjfyl']=round(100*$v2['yjsjtrfy']/$v2['hdxl'],2).'%';
            }else{
                $v2['yjfyl']=0;
            }

            $v2['sn']=$apply['sn'].'-'.$v2['sn'];
            $v2['title']=Db::name('cg_jxs')->where(['id'=>$v2['jxs_id']])->value('title');//经销商
            $v2['zxtime']=date('Y-m-d',$v2['start']).'至'.date('Y-m-d',$v2['end']);
            $v2['expCanTime']=date('Y-m-d',$v2['expCanTime']);
            $id2=$v2['cp_id'];
            switch ($v2['cp_type']){
                case 0:
                    $id2=$v2['brand'];
                    $cp=Db::name('pro_brands')->where(['id'=>$id2])->field('brand_name name')->find();
                    $v2['cp_name']=$cp['name'];  // $v2['cp_name']
                    $v2['cp_type']='品牌';
                    break;
                case 1:
                    $id2=$v2['category'];
                    $cp=Db::name('pro_category')->where(['id'=>$id2])->field('category_name name')->find();
                    $v2['cp_name']=$cp['name'];
                    $v2['cp_type']='品类';
                    break;
                case 2:
                    $id2=$v2['series'];
                    $cp=Db::name('pro_series')->where(['id'=>$id2])->field('series_name name')->find();
                    $v2['cp_name']=$cp['name'];
                    $v2['cp_type']='系列';
                    break;
                case 3:
                    $id2=$v2['sku'];
                    $cp=Db::name('pro_sku')->where(['id'=>$id2])->field('sku_name name')->find();
                    $v2['cp_name']=$cp['name'];
                    $v2['cp_type']='SKU';
                    break;
                case 4:
                    $id2=$v2['product'];
                    $cp=Db::name('pro_products')->where(['id'=>$id2])->field('pro_name name')->find();
                    $v2['cp_name']=$cp['name'];
                    $v2['cp_type']='单品';
                    break;

            }

            $v2['feetype']=Db::name('cg_feiyongkemu3')->where(['id'=>$v2['feetype']])->value('title');//
            $v2['paymethod']=Db::name('cg_paymethod')->where(['id'=>$v2['paymethod']])->value('title');

            if(isset($v2['payeetype'])&&$v2['payeetype']==1){
                $v2['payeetype']='经销商';
                $v2['payee']=DB::name('cg_jxs')->where(['id'=>$v2['payee']])->value('title');

            }elseif (isset($v2['payeetype'])&&$v2['payeetype']==2){
                $v2['payeetype']='供应商';
                $v2['payee']=DB::name('gys')->where('id',$v2['payee'])->value('gys_name');
            }

            if(isset($v2['cl_type'])&&!empty($v2['cl_type'])){
                $cl_type = [
                    ['title'=>'货架陈列','id'=>'1'],
                    ['title'=>'堆头陈列','id'=>'2'],
                    ['title'=>'端架陈列','id'=>'3'],
                    ['title'=>'包柱陈列','id'=>'4'],
                    ['title'=>'挂网陈列','id'=>'5'],
                    ['title'=>'其他陈列','id'=>'6'],
                ];

                foreach ($cl_type as $ck=>$cv){
                    if($v2['cl_type']==$cv['id']){
                        $v2['cl_type']=$cv['title'];
                    }
                }
            }else{
                $v2['cl_type']='';
            }

            if(isset($v2['cl_place'])&&!empty($v2['cl_place'])){
                $cl_place = [
                    ['title'=>'主通道','id'=>'1'],
                    ['title'=>'副通道','id'=>'2'],
                    ['title'=>'收银台','id'=>'3'],
                    ['title'=>'卖场门口','id'=>'4'],
                    ['title'=>'端架两侧','id'=>'5'],
                    ['title'=>'其他位置','id'=>'6'],
                ];

                foreach ($cl_place as $ck=>$cv){
                    if($v2['cl_place']==$cv['id']){
                        $v2['cl_place']=$cv['title'];
                    }
                }
            }else{
                $v2['cl_place']='';
            }

            if(isset($v2['cl_size'])&&!empty($v2['cl_size'])){
                $cl_size =[
                    ['title'=>'1m x 1m','id'=>'1'],
                    ['title'=>'2m x 1m','id'=>'2'],
                    ['title'=>'2m x 2m','id'=>'3'],
                    ['title'=>'4m x 1m','id'=>'4'],
                    ['title'=>'整节端架','id'=>'5'],
                    ['title'=>'半节端架','id'=>'6'],
                    ['title'=>'其他尺寸','id'=>'7'],
                ];

                foreach ($cl_size as $ck=>$cv){
                    if($v2['cl_size']==$cv['id']){
                        $v2['cl_size']=$cv['title'];
                    }
                }
            }else{
                $v2['cl_size']='';
            }

        }

        $this->assign("xxxx",$xxxx);
        $applynet = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->where("ap.id=$aid")
            ->field(" apd.ctime,ap.id,apd.start,apd.end,apd.brief,apd.cp_type,noSales,yesSales,feiyonglv,roi")
            ->group('apd.ctime')
            ->select();
        $feedate=['title'=>[],'hanshuis'=>[]];
        $all = ["hanshuis" => 0, "noSales" => 0, "yesSales" => 0, "feiyonglv" => 0, "hanshuis" => 0,"sellnums" => 0, "xiaoshoues" => 0, "buchas" => 0, "zonges" => 0,"jxscha"=>0,"netcha"=>0,"feiyonglv"=>0,"yujirois"=>0];
        //dump($applynet);die; //费用明细条数
        for ($i = 0; $i < count($applynet); $i++) {
            $applynet[$i]['daynum']=($applynet[$i]['end']-$applynet[$i]['start'])/(3600*24)+1;
            $applynet[$i]['start']=date('Y-m-d',$applynet[$i]['start']);
            $applynet[$i]['end']=date('Y-m-d',$applynet[$i]['end']);

            $id=$applynet[$i]['id'];
            $ctime=$applynet[$i]['ctime'];
            $cp_type=$applynet[$i]['cp_type'];
            switch ($cp_type){
                case 0:
                    $cp_type='brand';
                    $a = Db::table("cg_ti_list")->query("select id,cp_id,cp_type,brand as pro_name,category,series,sku,product,sum(net_id) as net_ids,sum(xt_id) as xt_ids  from  cg_ti_list as apd  where apd.ti_id=$id and apd.ctime=$ctime group by $cp_type");
                    $cptype='品牌';
                    $cp_name=array();
                    foreach ($a as $av=>$ak){
                        $cp=Db::name('pro_brands')->where(['id'=>$ak['pro_name']])->field('brand_name name')->find();
                        $cp_name[$av]=$cp['name'];
                    }
                    break;
                case 1:
                    $cp_type='category';
                    $a = Db::table("cg_ti_list")->query("select id,cp_id,cp_type,brand,category  as pro_name,series,sku,product,sum(net_id) as net_ids,sum(xt_id) as xt_ids  from  cg_ti_list as apd  where apd.ti_id=$id and apd.ctime=$ctime group by $cp_type");
                    $cptype='品类';
                    $cp_name=array();
                    foreach ($a as $av=>$ak){
                        $cp=Db::name('pro_category')->where(['id'=>$ak['pro_name']])->field('category_name name')->find();
                        $cp_name[$av]=$cp['name'];
                    }
                    break;
                case 2:
                    $cp_type='series';
                    $a = Db::table("cg_ti_list")->query("select id,cp_id,cp_type,brand,category,series  as pro_name,sku,product,sum(net_id) as net_ids,sum(xt_id) as xt_ids  from  cg_ti_list as apd  where apd.ti_id=$id and apd.ctime=$ctime group by $cp_type");
                    $cptype='系列';
                    $cp_name=array();
                    foreach ($a as $av=>$ak){
                        $cp=Db::name('pro_series')->where(['id'=>$ak['pro_name']])->field('series_name name')->find();
                        $cp_name[$av]=$cp['name'];
                    }
                    break;
                case 3:
                    $cp_type='sku';
                    $a = Db::table("cg_ti_list")->query("select id,cp_id,cp_type,brand,category,series,sku  as pro_name,product,sum(net_id) as net_ids,sum(xt_id) as xt_ids  from  cg_ti_list as apd  where apd.ti_id=$id and apd.ctime=$ctime group by $cp_type");
                    $cptype='SKU';
                    $cp_name=array();
                    foreach ($a as $av=>$ak){
                        $cp=Db::name('pro_sku')->where(['id'=>$ak['pro_name']])->field('sku_name name')->find();
                        $cp_name[$av]=$cp['name'];
                    }
                    break;
                case 4:
                    $cp_type='product';
                    $a = Db::table("cg_ti_list")->query("select id,cp_id,cp_type,brand,category,series,sku,product as pro_name,sum(net_id) as net_ids,sum(xt_id) as xt_ids   from  cg_ti_list as apd  where apd.ti_id=$id and apd.ctime=$ctime group by $cp_type");
                    //$a = Db::table("cg_ti_list")->query("select id,cp_id,cp_type,brand,category,series,sku,product,sum(net_id) as net_ids,sum(xt_id) as xt_ids  as pro_name  from  cg_ti_list as apd  where apd.ti_id=$id and apd.ctime=$ctime group by $cp_type");
                    $cptype='单品';
                    $cp_name=array();
                    foreach ($a as $av=>$ak){
                        $cp=Db::name('pro_products')->where(['id'=>$ak['pro_name']])->field('pro_name name')->find();
                        $cp_name[$av]=$cp['name'];
                    }
                    break;
            }
            $applynet[$i]['cp_name']=$cp_name;
            $applynet[$i]['cp_type']=$cptype;
            $applynet[$i]['cp_num']=count($a);
            $kh='';
            //客户详情-系统
            if(isset($a[0]['xt_ids'])&&!empty($a[0]['xt_ids'])){
                //$b = Db::table("cg_ti_list")->query("select xt_id,xt_zb,net_num  from  cg_ti_list as apd  where apd.ti_id=$id and apd.ctime=$ctime   group by apd.xt_id ");
                $b = Db::table("cg_ti_list")->query("select xt_id,xt_zb,net_num,sys.title  from  cg_ti_list as apd inner join cg_system as sys on apd.xt_id=sys.id where apd.ti_id=$id and apd.ctime=$ctime   group by apd.xt_id ");

                foreach ($b as $bk=>$bv){
                    $kh.='<p>'.$bv['title'].'/'.$bv['net_num'].'家</p>';
                }
                $kh.='<p class="spanTotal">共<span>'.count($b).'</span>个系统</p>';

            }
            //客户详情-网点
            if(isset($a[0]['net_ids'])&&!empty($a[0]['net_ids'])){
                $b = Db::table("cg_ti_list")->query("
                                select xt_zb,net_num,sys.title,count(net.id) as netnum,sys.id as sysid  
                                from  cg_ti_list as apd 
                                inner join cg_net as net on apd.net_id=net.id 
                                inner join cg_system as sys on net.system_id=sys.id 
                                where apd.ti_id=$id and apd.ctime=$ctime   
                                group by sys.id ");
                foreach ($b as $bk=>&$bv){
                    $sysid=$bv['sysid'];
                    $sql="select apd.id
                                 from  cg_ti_list as apd 
                                 inner join cg_net as net on apd.net_id=net.id 
                                 inner join cg_system as sys on net.system_id=sys.id 
                                 where sys.id=$sysid and apd.ctime=$ctime  and apd.ti_id=$id
                                 group by net.id";
                    $c = Db::table("cg_ti_list")->query($sql);
                    $kh.='<p>'.$bv['title'].'/'.count($c).'家</p>';
                }
                $kh.='<p class="spanTotal">共<span>'.count($b).'</span>个系统</p>';
            }
            if(!empty($kh)){
                $applynet[$i]['kh']=$kh;
            }else{
                $applynet[$i]['kh']='-';////客户详情-经销商
            }

            //费用类型
            $sql="select apd.feetype,fy.title,apd.payee,apd.payeetype,apd.paymethod,pay.title as payname,apd.feiyongmiaoshu,apd.amount,apd.cl_type,apd.cl_place,apd.cl_size,sum(apd.hanshui) as hanshuis
                                 from  cg_ti_list as apd 
                                 inner join cg_feiyongkemu3 as fy on apd.feetype=fy.id
                                 inner join cg_paymethod as pay on apd.paymethod=pay.id  
                                 where  apd.ctime=$ctime  and apd.ti_id=$id
                                 group by apd.feetype";//anp

            $c = Db::table("cg_ti_list")->query($sql);
            $applynet[$i]['feenum']=count($c);
            $applynet[$i]['fee']=$c;
        }
        foreach ($applynet as $ak=>$av){
            foreach ($av['fee'] as $fk=>$fv){
                $all["hanshuis"] += $fv["hanshuis"];
                array_push($feedate['title'],$fv["title"]);
                array_push($feedate['hanshuis'],$fv["hanshuis"]);
            }
            $all["noSales"] += $av["noSales"];
            $all["yesSales"] += $av["yesSales"];
        }
        if($all['yesSales']!=0){
            $all['feiyonglv'] = round(100*$all['hanshuis']/$all['yesSales'],2).'%';
        }
        $this->assign("applyde", $applynet);

        $this->assign("all", $all);

        $feeda=[[]];
        foreach ($feedate['title'] as $fek=>$fev){
            $feeda[$fek]=['title'=>$fev,'hanshuis'=>$feedate['hanshuis'][$fek]];
        }
        if(empty($feeda[0])){
            $feeda=[];
        }

        $this->assign("feeda",$feeda);
        $cainian=db("cg_cainian")->order("starttime desc")->select();
        $now=strtotime(date("Y-m-d"));
        $cid=db("cg_cainian")->where("starttime<=$now and endtime>=$now")->value("id");
        $this->assign("cainian",$cainian);
        $this->assign("cid",$cid);
        $kaohe2=db("cg_kaoheqi2 k2")->join("cg_kaoheqi1 k1","k2.pid=k1.id")->where("k1.cid=$cid")->order("k2.starttime")->field("k2.id,k2.title")->select();
        $this->assign("kaohe2",$kaohe2);
        $k2id=db("cg_kaoheqi2")->where("starttime<=$now and endtime>=$now")->value("id");
        $this->assign("k2id",$k2id);
        $nearhuodong=$this->zuijinhuodong($cid,$k2id,$k2id,$aid);
        $this->assign("nearhuodong",$nearhuodong);
        $jxsjc1=$this->getjxtj($cid,$k2id,$k2id,$aid);
        $this->assign("jxsjc1",$jxsjc1);
        $kemu=db("cg_ti_list")->where(["ti_id"=>$aid])->group("feetype")->field("feetype id,sum(hanshui) as fy")->select();
        for($i=0;$i<count($kemu);$i++){ 
            $kemu[$i]["title"]=db("cg_feiyongkemu3")->where(["id"=>$kemu[$i]["id"]])->value("title");
        }
        $jc=db("cg_ti_list")->where(["ti_id"=>$aid,'fylx'=>7])->count();
        //echo $jc;die;
        /*if(empty($jc)){
            $jc='';
        }else{
            $jc=1;
        }*/
        $this->assign("jc",$jc);
        $this->assign("kemu",$kemu);
       $jxsjc2=$this->getjxmx($cid,$k2id,$k2id,$aid);
        $this->assign("jxsjc2",$jxsjc2);
        return $this->fetch();

    }




    public function jxsjc2($cid,$k2s,$k2e,$aid){
        $arr=$this->getjxmx($cid,$k2s,$k2e,$aid);
        return json_encode($arr);
    }
    //经销商费用与销量明细
    public function getjxmx($cid,$k2s,$k2e,$aid){
         $start=db("cg_kaoheqi2")->where(["id"=>$k2s])->value("starttime");
        $end=db("cg_kaoheqi2")->where(["id"=>$k2e])->value("endtime");
        $apply=Db::Table("cg_ti")->where(["id"=>$aid])->find();
        $jxs=Db::table("cg_jxs")->where(["id"=>$apply["jxs_id"]])->find();
        //当年考核期
        $where="k1.cid=$cid and k2.starttime>=$start and k2.endtime<=$end";
        $kao2=Db::table("cg_kaoheqi1")->alias("k1")->join("cg_kaoheqi2 k2","k2.pid=k1.id")->where($where)->order("k2.starttime")
        ->field("k1.id as k1id,k1.title as k1title,k1.starttime as k1start,k1.endtime as k1end,k2.id as k2id,k2.title as k2title,k2.starttime as k2start,k2.endtime as k2end")->select();
         $ys=0;
        for($i=0;$i<count($kao2);$i++){
            $ys++;
            //计算天数
            $k1ts=($kao2[$i]["k1end"]-$kao2[$i]["k1start"])/3600/24+1;
            $k2ts=($kao2[$i]["k2end"]-$kao2[$i]["k2start"])/3600/24+1;
            //当年目标
       
            $kao2[$i]["tar"]=0;
            $sumk2tar=Db::table("target_apply")->alias("t")->join("target_apply_detail td","td.apply_id=t.id")
            ->where("t.type_id=5 and t.state=7 and t.tag<>1 and t.is_actived=1 and t.is_deleted=0 and td.jingxiao={$jxs["id"]} and td.erjikaoheqi={$kao2[$i]["k2id"]}")->sum("feiyong");
            if($sumk2tar)
                $kao2[$i]["tar"]+=$sumk2tar;
            $sumk1tar=Db::table("target_apply")->alias("t")->join("target_apply_detail td","td.apply_id=t.id")
            ->where("t.type_id=5 and t.state=7 and t.tag<>1 and t.is_actived=1 and t.is_deleted=0 and td.jingxiao={$jxs["id"]} and td.yijikaoheqi={$kao2[$i]["k1id"]} and td.erjikaoheqi is null")->sum("feiyong");
            //echo Db::table("target_apply")->getLastsql();
            if($sumk1tar){
                $kao2[$i]["tar"]+=$sumk1tar/$k1ts*$k2ts;
            }
             //预算费用
             $kao2[$i]["ys"]=0;
            $sumk2ys=Db::Table("yusuan")->alias("y")->where("y.type=1 and y.jingxiao={$jxs["id"]} and erjikaoheqi={$kao2[$i]["k2id"]}")->sum("jine");
            if($sumk2ys){
                $kao2[$i]["ys"]+=$sumk2ys;
            }
            $sumk1ys=Db::Table("yusuan")->alias("y")->where("y.type=1 and y.jingxiao={$jxs["id"]} and yijikaoheqi={$kao2[$i]["k1id"]} and erjikaoheqi is null")->sum("jine");
            if($sumk1ys){
                $kao2[$i]["ys"]+=$sumk1ys/$k1ts*$k2ts;
            }
             //投入额
          
            $sumks=Db::table("cg_ti")->alias("t")
            ->join("cg_ti_list td","t.id=td.ti_id")
            ->where("t.status in (7,9) and t.status2 is null and (td.isOrNo is null or td.isOrNo=1) and td.start>={$kao2[$i]["k2start"]} and td.start<={$kao2[$i]["k2end"]} and t.jxs_id={$jxs["id"]}")->field("pizhunhanshui,totalExpectedSales,fb_shijitourufeiyong,fb_shijixiaoliang")->select();
            $kao2[$i]["sjxl"]=0;$kao2[$i]["yiyong"]=0;$kao2[$i]["dacheng"]=0;$kao2[$i]["mbfyl"]=0;$kao2[$i]["sjfyl"]=0;
            foreach ($sumks as $k => $v) {
                # code...
                if($v["fb_shijixiaoliang"]){
                    $kao2[$i]["sjxl"]+=$v["fb_shijixiaoliang"];
                }else{
                    $kao2[$i]["sjxl"]+=$v["totalExpectedSales"];
                }
                if($v["fb_shijitourufeiyong"]){
                    $kao2[$i]["yiyong"]+=$v["fb_shijitourufeiyong"];

                }else{
                    $kao2[$i]["yiyong"]+=$v["pizhunhanshui"];
                }

            }
            $kao2[$i]["yiyong"]=round($kao2[$i]["yiyong"],2);
            $kao2[$i]["sjxl"]=round($kao2[$i]["sjxl"],2);
            if($kao2[$i]["tar"]){
                $kao2[$i]["dacheng"]=round($kao2[$i]["sjxl"]/$kao2[$i]["tar"]*100,2);
            }
            if($kao2[$i]["tar"]&&$kao2[$i]["ys"]){
                $kao2[$i]["mbfyl"]=round($kao2[$i]["ys"]/$kao2[$i]["tar"]*100,2);
            }
            if($kao2[$i]["yiyong"]&&$kao2[$i]["sjxl"]){
                $kao2[$i]["sjfyl"]=round($kao2[$i]["yiyong"]/$kao2[$i]["sjxl"]*100,2);
            }
        }
        return $kao2;
    }
    public function jxsjc1($cid,$k2s,$k2e,$aid){
        $arr=$this->getjxtj($cid,$k2s,$k2e,$aid);
        return json_encode($arr);
    }
    //经销商费用与销量统计
    public function getjxtj($cid,$k2s,$k2e,$aid){
        $start=db("cg_kaoheqi2")->where(["id"=>$k2s])->value("starttime");
        $end=db("cg_kaoheqi2")->where(["id"=>$k2e])->value("endtime");
        $apply=Db::Table("cg_ti")->where(["id"=>$aid])->find();
        $jxs=Db::table("cg_jxs")->where(["id"=>$apply["jxs_id"]])->find();
        //当年考核期
        $where="k1.cid=$cid and k2.starttime>=$start and k2.endtime<=$end";
        $kao2=Db::table("cg_kaoheqi1")->alias("k1")->join("cg_kaoheqi2 k2","k2.pid=k1.id")->where($where)->order("k2.starttime")
        ->field("k1.id as k1id,k1.title as k1title,k1.starttime as k1start,k1.endtime as k1end,k2.id as k2id,k2.title as k2title,k2.starttime as k2start,k2.endtime as k2end")->select();
        //echo db("cg_kaoheqi1")->getLastsql();exit;
        $zong["tr"]=0;$zong["ys"]=0;$zong["sjxl"]=0;$zong["dacheng"]=0;$zong["yiyong"]=0;$zong["mbfyl"]=0;$zong["sjfyl"]=0;
        $ys=0;

        for($i=0;$i<count($kao2);$i++){
            $ys++;
            //计算天数
            $k1ts=($kao2[$i]["k1end"]-$kao2[$i]["k1start"])/3600/24+1;
            $k2ts=($kao2[$i]["k2end"]-$kao2[$i]["k2start"])/3600/24+1;
            //当年目标
            $kao2[$i]["tar"]=0;
            $sumk2tar=Db::table("target_apply")->alias("t")->join("target_apply_detail td","td.apply_id=t.id")
            ->where("t.type_id=5 and t.state=7 and t.tag<>1 and t.is_actived=1 and t.is_deleted=0 and td.jingxiao={$jxs["id"]} and td.erjikaoheqi={$kao2[$i]["k2id"]}")->sum("feiyong");
            if($sumk2tar)
                $kao2[$i]["tar"]+=$sumk2tar;
            $sumk1tar=Db::table("target_apply")->alias("t")->join("target_apply_detail td","td.apply_id=t.id")
            ->where("t.type_id=5 and t.state=7 and t.tag<>1 and t.is_actived=1 and t.is_deleted=0 and td.jingxiao={$jxs["id"]} and td.yijikaoheqi={$kao2[$i]["k1id"]} and td.erjikaoheqi is null")->sum("feiyong");
            //echo Db::table("target_apply")->getLastsql();
            if($sumk1tar){
                $kao2[$i]["tar"]+=$sumk1tar/$k1ts*$k2ts;
            }
            $zong["tr"]+=$kao2[$i]["tar"];
            //预算费用
            $kao2[$i]["ys"]=0;
            $sumk2ys=Db::Table("yusuan")->alias("y")->where("y.type=1 and y.jingxiao={$jxs["id"]} and erjikaoheqi={$kao2[$i]["k2id"]}")->sum("jine");
            if($sumk2ys){
                $kao2[$i]["ys"]+=$sumk2ys;
            }
            $sumk1ys=Db::Table("yusuan")->alias("y")->where("y.type=1 and y.jingxiao={$jxs["id"]} and yijikaoheqi={$kao2[$i]["k1id"]} and erjikaoheqi is null")->sum("jine");
            if($sumk1ys){
                $kao2[$i]["ys"]+=$sumk1ys/$k1ts*$k2ts;
            }
            $zong["ys"]+=$kao2[$i]["ys"];
             //投入额
          
            $sumks=Db::table("cg_ti")->alias("t")
            ->join("cg_ti_list td","t.id=td.ti_id")
            ->where("t.status in (7,9) and t.status2 is null and (td.isOrNo is null or td.isOrNo=1) and td.start>={$kao2[$i]["k2start"]} and td.start<={$kao2[$i]["k2end"]} and t.jxs_id={$jxs["id"]}")->field("pizhunhanshui,totalExpectedSales,fb_shijitourufeiyong,fb_shijixiaoliang")->select();
            foreach ($sumks as $k => $v) {
                # code...
                if($v["fb_shijixiaoliang"]){
                    $zong["sjxl"]+=$v["fb_shijixiaoliang"];
                }else{
                    $zong["sjxl"]+=$v["totalExpectedSales"];
                }
                if($v["fb_shijitourufeiyong"]){
                    $zong["yiyong"]+=$v["fb_shijitourufeiyong"];
                }else{
                    $zong["yiyong"]+=$v["pizhunhanshui"];
                }
            }
        }
        $zong["tr"]=round($zong["tr"],2);
        $zong["ys"]=round($zong["ys"],2);
        $zong["yiyong"]=round($zong["yiyong"],2);
        $zong["sjxl"]=round($zong["sjxl"],2);
        if($zong["tr"]){
            $zong["dacheng"]=round($zong["sjxl"]/$zong["tr"]*100,2);
        }
        if($zong["tr"]&&$zong["ys"]){
            $zong["mbfyl"]=round($zong["ys"]/$zong["tr"]*100,2);
        }
        if($zong["sjxl"]&&$zong["yiyong"]){
            $zong["sjfyl"]=round($zong["yiyong"]/$zong["sjxl"]*100,2);
        }

        //print_r($zong);exit;
        return $zong;
    }
    public function getxg($cid,$k2s,$k2e,$aid){
        $arr=$this->zuijinhuodong($cid,$k2s,$k2e,$aid);
        return json_encode($arr);
    }
    //最近活动
    public function zuijinhuodong($cid,$k2s,$k2e,$aid){
        $start=db("cg_kaoheqi2")->where(["id"=>$k2s])->value("starttime");
        $end=db("cg_kaoheqi2")->where(["id"=>$k2e])->value("endtime");
        $where="ctime>=$start and ctime<=$end and status in (2,3,4,5,6,7) and (status2 is null or status2=0) ";
        $apply=db("cg_ti")->where(["id"=>$aid])->find();
        $jxs=$apply["jxs_id"];
        $city=db("cg_jxs")->where(["id"=>$jxs])->value("city");
        $jxslists=db("cg_jxs")->where(["city"=>$city])->column("id");
        $jxscont=db("cg_jxs")->where(["id"=>$jxs])->value("title");
        $citycont=db("cg_market_city")->where(["id"=>$city])->value("title");
        $cuser=$apply["cuser"];
        //print_r($jxslists);exit; 
        $data=[];
        
        $jxsstr=implode(',',$jxslists);
        //本城市
        $where1=$where."and jxs_id in ($jxsstr)";
        $tmp1=db("cg_ti")->where($where1)->field("id,sn,title,status,jxs_id,type_id")->order("ctime desc")->select();
        foreach ($tmp1 as $k => $v) {

                # code...
            $tmp1[$k]["jxs"]=$jxscont;
            $tmp1[$k]["city"]=$citycont;
            $tmp1[$k]["type"]=1;
            $data[]=$tmp1[$k];
                
        }
        //本客户
        $where2=$where."and jxs_id=$jxs";
        $tmp2=db("cg_ti")->where($where2)->field("id,sn,title,status,jxs_id,type_id")->order("ctime desc")->select();
        foreach ($tmp2 as $k => $v) {
                # code...
            $tmp2[$k]["jxs"]=$jxscont;
            $tmp2[$k]["city"]=$citycont;
            $tmp2[$k]["type"]=2;
            $data[]=$tmp2[$k];
                
        }
        //本业务员
        $where3=$where."and cuser=$cuser";
        $tmp3=db("cg_ti")->where($where3)->field("id,sn,title,status,jxs_id,type_id")->order("ctime desc")->select();
        foreach ($tmp3 as $k => $v) {
                # code...
            $tmpjxs=db("cg_jxs")->where(["id"=>$v["jxs_id"]])->field("title,city")->find();
            $tmp3[$k]["jxs"]=$tmpjxs["title"];
            $tmp3[$k]["city"]=db("cg_market_city")->where(["id"=>$tmpjxs["city"]])->value("title");
            $tmp3[$k]["type"]=3;
            $data[]=$tmp3[$k];
                
        }
        //print_r($data);exit;
        foreach ($data as $k => $v) {
            # code...
            $kemu=db("cg_ti_list")->where(["ti_id"=>$v["id"]])->group("feetype")->column("feetype");
            $kemu=implode(",",$kemu);
            if($kemu){
                $kemu=db("cg_feiyongkemu3")->where("id in ($kemu)")->column("title");
                $kemu=implode(',',$kemu);
            }else{
                $kemu="";
            }
            
            $data[$k]["kemu"]=$kemu;
            $list=db("cg_ti_list")->where(["ti_id"=>$v["id"]])->field("yjsjtrfy,fb_shijitourufeiyong,totalExpectedSales,fb_shijixiaoliang,yujiroi")->select();
            $zongfeiyong=0;
            $zongxiaoliang=0;
            $roi=0;
            foreach ($list as $kl => $vl) {
                # code...
                if($vl["fb_shijitourufeiyong"]){
                    $zongfeiyong+=$vl["fb_shijitourufeiyong"];
                    $roi+=$vl["fb_shijitourufeiyong"]*$vl["yujiroi"];
                }else{
                    $zongfeiyong+=$vl["yjsjtrfy"];
                    $roi+=$vl["yjsjtrfy"]*$vl["yujiroi"];
                }
                if($vl["fb_shijixiaoliang"]){
                    $zongxiaoliang+=$vl["fb_shijixiaoliang"];
                }else{
                    $zongxiaoliang+=$vl["totalExpectedSales"];
                }
            }
            $data[$k]["feiyonge"]=$zongfeiyong;
            if($zongxiaoliang)
                $data[$k]["feiyonglv"]=round($zongfeiyong/$zongxiaoliang*100,2);
            else
                $data[$k]["feiyonglv"]=0;
            if($zongfeiyong)
                $data[$k]["roi"]=round($roi/$zongfeiyong,2);
            else
                $data[$k]["roi"]=0;
            if($data[$k]["status"]==2){
                $data[$k]["status"]="打回修改";
            }else if($data[$k]["status"]==7){
                $data[$k]["status"]="已通过";
            }else{
                $data[$k]["status"]="审批中";
            }
        }
        return $data;
        
    }
    public function niantok2($cid){
        $kaohe2=db("cg_kaoheqi2 k2")->join("cg_kaoheqi1 k1","k2.pid=k1.id")->where("k1.cid=$cid")->order("k2.starttime")->field("k2.id,k2.title")->select();
        return json_encode($kaohe2);
    }
    public function tpmbacklogdetail(){
        $workId = $this->request->param('workId');
        $trackId = $this->request->param('trackId');
        $myId = $this->request->param('myId');
//yw_id
        $yw_id =db('cg_workflow')->where('id',$myId)->value('yw_id');

        $this->assign('yw_id',$yw_id);
        $state=db("cg_ti")->where(["id"=>$yw_id])->value("status");
        if($state==2){
            //打回
            $this->redirect('TiApply/addform', ['aid' => $yw_id,"from"=>2]);
            return;
        }
        //打开工作流
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['workId'] = $workId;
        $post_data['trackId'] = $trackId;
        $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$post_data);
        $data = object_array($data);
        $this->assign('data',$data);

        $info = db('cg_ti')->where('id',$yw_id)->find();
        $info['jxs_name'] = db('cg_jxs')->where('id',$info['jxs_id'])->value('title');
        $info['sqr'] = db('employee')->where('id',$info['cuser'])->value('em_name');
        $info['sqr_job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->where('t2.employee_id',$info['cuser'])->value('t.job_name');
        $info['zoning'] = db('cg_market_zoning t')->join('cg_jxs t2','t2.zoning=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['provice'] = db('cg_market_provice t')->join('cg_jxs t2','t2.provice=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['city'] = db('cg_market_city t')->join('cg_jxs t2','t2.city=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['jxs_type'] = db('cg_jxs_types t')->join('cg_jxs t2','t2.types=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['start'] = db('cg_ti_list')->where('ti_id',$yw_id)->value('start');
        $info['end'] = db('cg_ti_list')->where('ti_id',$yw_id)->value('end');
        $info['is_bu'] = db('cg_ti_list')->where('ti_id',$yw_id)->value('is_bu');
        if($info['productlat']==1){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'brand'=>['exp','is not null']])->value('brand');
            $info['pro_label'] = '品牌';
            $info['pro_name'] = db('pro_brands')->where('id',$brand_id)->value('brand_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->group("brand")->count('brand');
        }elseif($info['productlat']==2){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'category'=>['exp','is not null']])->value('category');
            $info['pro_label'] = '品类';
            $info['pro_name'] = db('pro_category')->where('id',$brand_id)->value('category_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->group("category")->count('category');
        }elseif($info['productlat']==3){
            $info['pro_label'] = '系列';
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'series'=>['exp','is not null']])->value('series');
            $info['pro_name'] = db('pro_series')->where('id',$brand_id)->value('series_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->group("series")->count('series');
        }elseif($info['productlat']==4){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'sku'=>['exp','is not null']])->value('sku');
            $info['pro_label'] = 'sku';
            $info['pro_name'] = db('pro_sku')->where('id',$brand_id)->value('sku_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->group("sku")->count('sku');
        }elseif($info['productlat']==5){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'product'=>['exp','is not null']])->value('product');
            $info['pro_label'] = '产品';
            $info['pro_name'] = db('pro_products')->where('id',$brand_id)->value('pro_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->group("product")->count('product');
        }



        $apply=Db::table("cg_ti")->where(["id"=>$yw_id])->find();
        $net_num = Db::table("cg_ti_list")->where(["ti_id"=>$yw_id])->group("net_id")->count();
        $this->assign("net_num", $net_num);
        $system_num=Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")
            ->join("cg_system s", "n.system_id=s.id", "LEFT")->where(["ap.id" => $yw_id])->group("s.id")->count();
        $this->assign("system_num",$system_num);
        $applyde=Db::table("cg_ti_list")->where(["ti_id"=>$yw_id])->select();
        $info["xitong"]=Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")
            ->join("cg_system s", "n.system_id=s.id", "LEFT")->where(["ap.id" => $yw_id])->value("s.title");

        $info["xitongtype"]=Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")
            ->join("cg_system s", "n.system_id=s.id", "LEFT")->join("cg_customertype t","s.cusType=t.id")->where(["ap.id" => $yw_id])->value("t.title");
        $info["net"]=Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")->where(["ap.id" => $yw_id])->value("n.title");
        $info["nettype"]=Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")->join("cg_networktype cn","n.cat=cn.id")->where(["ap.id" => $yw_id])->value("cn.title");
        //查看活动是否重复--判断是否存在费用类型相同收款方也相同的情况
        /*$cnt1 = Db::query('SELECT count(*) cnt from (SELECT gys,count(gys) AS count FROM cg_ti_list where ti_id='.$yw_id.' and gys is not null GROUP BY feetype,payee HAVING count > 1) t');
        $cnt1 = $cnt1[0]['cnt'];

        $info['iscf'] =$cnt1;*/

        $this->assign('info',$info);



        /**
         * 活动列表--start
         */
        /*$ti_list = db('cg_ti_list')->where('ti_id',$yw_id)->field('start,end,feetype,product,brand,category,series,sku,yjsjtrfy,totalExpectedSales,paymethod')->select();
        foreach($ti_list as $k=>$v){
            $v['feetype_name'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
            if($v['product'])
                $v['product_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
            elseif($v['brand'])
                $v['product_name'] = db('pro_brands')->where('id',$v['brand'])->value('brand_name');
            elseif($v['category'])
                $v['product_name'] = db('pro_category')->where('id',$v['category'])->value('category_name');
            elseif($v['series'])
                $v['product_name'] = db('pro_series')->where('id',$v['series'])->value('series_name');
            elseif($v['sku'])
                $v['product_name'] = db('pro_sku')->where('id',$v['sku'])->value('sku_name');
            $v['yjfyl'] = round($v['yjsjtrfy']/$v['totalExpectedSales']*100,2);
            $v['zffs'] = db('cg_paymethod')->where('id',$v['paymethod'])->value('title');
            $ti_list[$k] = $v;
        }
        $this->assign('ti_list',$ti_list);*/
        /**
         * 活动列表--end
         */

        //本次申请已耗时
        $time = time()-$info['ctime'];
        $bcsqhs = $this->vtime($time);
        $this->assign('bcsqhs',$bcsqhs);

        //获取操作记录
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['workId'] = $workId;
        $czjl = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/history.wf',$post_data);
        $czjl = object_array($czjl);
//        echo "<pre>";print_r($czjl);
        foreach($czjl as $k=>$v){
            //查询审批意见
            $wf_id = 0;
//            $v['spyj'] = db('cg_workflow_spyj')->where(['wf_id'=>$wf_id,'spr_id']);
        }
        $this->assign('czjl',$czjl);

        //查询附件
        $attachs = db('cg_workflow_spyj')->where('wf_id',$myId)->column('attach');
        if($attachs){
            $attach = [];
            foreach($attachs as $item){
                if($item){
                    $item = unserialize($item);
                    foreach($item as $k=>$v){
                        $temp = Db::table('annex')->where(array('id'=>$v))->find();
                        $temp['path'] = '/uploads/'.$temp['path'];
                        $item[$k] = $temp;
                    }
                    $attach = array_merge($attach,$item);
                }
            }

            $this->assign('attach',$attach);

        }
        $prolist= Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("pro_products p", "apd.product=p.id")
            ->join("pro_sku sk", "p.sku_id=sk.id")
            ->join("pro_series ps", "sk.series_id=ps.id")
            ->join("pro_category pc","ps.category_id=pc.id")
            ->join("pro_brands pb","pc.brand_id=pb.id")->where(["ap.id" => $yw_id])->group("apd.product")
            ->field("pro_name,sku_name,brand_name,p.box_num,sum(apd.boxnum) as xiaoliang,sum(apd.totalExpectedSales) as xiaoshoue,sum(apd.totalBenchmarkSales) as jizhun,sum(hanshui) as hanshuis,pb.profit,apd.product,sum(yjsjtrfy) as pizhunhanshuis")->select();
        $heji["xiaoliang"]=0;$heji["xiaoshoue"]=0;$heji["jizhun"]=0;$heji["hanshuis"]=0;$heji["pizhunhanshuis"]=0;
        for($i=0;$i<count($prolist);$i++){
            $heji["xiaoliang"]+=$prolist[$i]["xiaoliang"];
            $heji["xiaoshoue"]+=$prolist[$i]["xiaoshoue"];
            $heji["jizhun"]+=$prolist[$i]["jizhun"];
            $heji["hanshuis"]+=$prolist[$i]["hanshuis"];$heji["pizhunhanshuis"]+=$prolist[$i]["pizhunhanshuis"];
            $prolist[$i]["feiyonglv"]=$prolist[$i]["hanshuis"]/$prolist[$i]["xiaoshoue"]*100;
            $prolist[$i]["roi"]=($prolist[$i]["xiaoshoue"]-$prolist[$i]["jizhun"])*$prolist[$i]["profit"]/$prolist[$i]["hanshuis"]/100;
            $prolist[$i]["feec"]=Db::table("cg_ti")->alias("ap")
                ->join("cg_ti_list apd", "apd.ti_id=ap.id")->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")->where(["ap.id" => $yw_id,"apd.product"=>$prolist[$i]["product"]])
                ->group("f3.id")->count();
            $prolist[$i]["fee"]=Db::table("cg_ti")->alias("ap")
                ->join("cg_ti_list apd", "apd.ti_id=ap.id")->join("cg_feiyongkemu3 k3", "apd.feetype=k3.id")
                ->join("cg_feiyongkemu2 k2","k3.pid=k2.id")->where(["ap.id" => $yw_id,"apd.product"=>$prolist[$i]["product"]])
                ->group("k3.id")->field("k3.title as kemu3,k2.title as kemu2,sum(hanshui) as hanshuis")->select();


        }

        $this->assign("heji",$heji);
        $this->assign("prolist",$prolist);

        //费用类型
        $info['fylx'] = Db::query('select count(*) cnt from (select feetype from cg_ti_list where ti_id='.$yw_id.' group by feetype) t')[0]['cnt'];
        $info['fylx_name'] = db('cg_ti_list t')->join('cg_feiyongkemu3 t2','t2.id=t.feetype')->where('ti_id',$yw_id)->value('t2.title');
        $info['fye'] = $heji["pizhunhanshuis"];
        $info['xl'] = $heji["xiaoshoue"];
//p($info);
        // $info['fyl'] = round($info['fye']/$info['xl']*100,2);
        $info['fyl']=999;
        $gs = db('cg_ti_list')->where(['ti_id'=>$yw_id])->count();
        $yujiroi = db('cg_ti_list')->where(['ti_id'=>$yw_id])->sum('yujiroi*yjsjtrfy');
        if($heji["pizhunhanshuis"])
            $info['roi'] = round($yujiroi/$heji["pizhunhanshuis"],2);
        else
            $info['roi'] = 0;
        /**
         *问题点--start
         */
        $wtd = [];$checkwt["fyl"]=0;$checkwt["roi"]=0;$checkwt["fanwei"]=0;$checkwt["ys"]=0;
        //公司建议的TI活动最高费用率值
        $feiYongLv = db('system_param')->where(['t'=>0,'k'=>'feiYongLv'])->value('v');
        if($info['fyl']>$feiYongLv){
            $checkwt["fyl"]=1;
            $wtd[] = '本申请单费用率不符合公司规定，公司规定为：'.$feiYongLv.'%';
        }
        //公司建议的TI活动ROI合格值
        $minRoi = db('system_param')->where(['t'=>0,'k'=>'minRoi'])->value('v');
        if($info['roi']<$minRoi){
            $wtd[] = '本申请单ROI低于公司规定，公司规定最小值为：'.$minRoi.'%';
            $checkwt["roi"]=1;
        }
        //公司建议的TI活动ROI较优值
        $maxRoi = db('system_param')->where(['t'=>0,'k'=>'maxRoi'])->value('v');
        if($info['roi']>$maxRoi){
            $wtd[] = '本申请单ROI高于公司规定，公司规定最大值为：'.$maxRoi.'%';
            $checkwt["roi"]=2;
        }
        //未设定完全价格体系的产品是否存在
        $nop=db("cg_ti_list")->alias("apd")->join("pro_products p", "apd.product=p.id")->join("pro_price pp","pp.pid=p.id")
            ->where("(pp.retail_low is null or pp.retail_low=0 or retail_high=0 or retail_high is null or pp.promotion_high is null or pp.promotion_high=0 or promotion_low is null or promotion_low=0) and apd.ti_id={$yw_id}")
            ->group("apd.product")->field("p.pro_name,apd.wangdian_price,pp.retail_low,pp.retail_high,pp.promotion_high,pp.promotion_low")->select();
        //print_r($nop);
        if($nop){
            $checkwt["fanwei"]=1;
            for($i=0;$i<count($nop);$i++){
                $wtd[] ="本申请中产品:{$nop[$i]["pro_name"]} 的定价体系未设定完全";
            }
        }
        //网点定价不在合法范围内
        $netout=db("cg_ti_list")->alias("apd")->join("pro_products p", "apd.product=p.id")->join("pro_price pp","pp.pid=p.id")->where(["netout"=>1,"ti_id" => $yw_id])
            ->group("p.id")->field("p.pro_name,apd.wangdian_price,pp.retail_low,pp.retail_high")->select();
        if($netout){
            $checkwt["fanwei"]=2;
            for($i=0;$i<count($netout);$i++){
                $wtd[] ="本申请中产品:{$netout[$i]["pro_name"]} 的网点供货价不符合公司规定的范围({$netout[$i]["retail_low"]}~{$netout[$i]["retail_high"]})";
            }
        }
        //活动零售价不再合法范围内
        $huodongout=db("cg_ti_list")->alias("apd")->join("pro_products p", "apd.product=p.id")->join("pro_price pp","pp.pid=p.id")->where(["huodongout"=>1,"ti_id" => $yw_id])
            ->group("p.id")->field("p.pro_name,apd.huodong_price,pp.promotion_high,pp.promotion_low")->select();
        if($huodongout){
            $checkwt["fanwei"]=2;
            for($i=0;$i<count($huodongout);$i++){
                $wtd[] ="本申请中产品:{$huodongout[$i]["pro_name"]} 的促销活动价不符合公司规定的范围({$huodongout[$i]["promotion_low"]}~{$huodongout[$i]["promotion_high"]})";
            }
        }
        //运算按照明细合并
        $yusuan=Db::table("yusuan_detail")->alias("yd")->join("yusuan y","yd.yid=y.id")
            ->where(["yd.aid"=>$yw_id,"y.type"=>1])->group("yd.did")->field("yd.aid,yd.did,sum(yd.jine) as jine,sum(yd.tianshu) as tianshu,max(yd.zongtianshu) as zongtianshu")
            ->select();
        // print_r($yusuan);
        $flag1=0;//是否所有明细都有匹配预算

        if(count($applyde)>count($yusuan)){
            //echo 1;
            $flag1=1;
        }

        for($i=0;$i<count($yusuan);$i++){
            if($yusuan[$i]["tianshu"]<$yusuan[$i]["zongtianshu"]){
                //echo 2;
                $flag1=1;
            }
        }
        //echo $flag1;
        if($flag1==1){
            $checkwt["ys"]=1;//未设定预算
            $wtd[] ="本申请中存在未设定预算的明细";
        }
        $flag2=0;//超出预算情况
        $yusuande=Db::table("yusuan_detail")->alias("yd")->join("yusuan y","yd.yid=y.id")
            ->where(["yd.aid"=>$yw_id,"y.type"=>1])->group("y.id")->field("y.id,y.jine,sum(yd.jine) as sjine,y.yijikaoheqi,y.erjikaoheqi,y.cainian,y.channel1,y.pinpai,y.erjifeiyong")->select();
        //预算明细处理

        for($i=0;$i<count($yusuande);$i++){
            //已通过预算的使用金额
            $yusuande[$i]["ytongguo"]=round(Db::table("yusuan_detail")->where(["yid"=>$yusuande[$i]["id"],"type"=>2])->sum("jine"),2);
            if(!$yusuande[$i]["ytongguo"])
                $yusuande[$i]["ytongguo"]=0;
            //申请中的预算使用金额
            $yusuande[$i]["shenqingzhong"]=round(Db::table("yusuan_detail")->where(["yid"=>$yusuande[$i]["id"],"type"=>1])->sum("jine"),2);
            if(!$yusuande[$i]["shenqingzhong"])
                $yusuande[$i]["shenqingzhong"]=0;
            if($yusuande[$i]["ytongguo"]>=$yusuande[$i]["jine"]){
                $yusuande[$i]["deng"]=2;
                $flag2=2;
            }else if($yusuande[$i]["ytongguo"]+$yusuande[$i]["shenqingzhong"]>$yusuande[$i]["jine"]){
                $yusuande[$i]["deng"]=1;
                if($flag2<2)
                    $flag2=1;
            }else{
                $yusuande[$i]["deng"]=0;
            }

            $yusuande[$i]["cainian"]=Db::table("cg_cainian")->where(["id"=>$yusuande[$i]["cainian"]])->value("title");
            if($yusuande[$i]["erjikaoheqi"]){

                $yusuande[$i]["kaoheqi"]=Db::table("cg_kaoheqi2")->where(["id"=>$yusuande[$i]["erjikaoheqi"]])->value("title");
            }else{

                $yusuande[$i]["kaoheqi"]=Db::table("cg_kaoheqi1")->where(["id"=>$yusuande[$i]["yijikaoheqi"]])->value("title");
            }
            $yusuande[$i]["channel"]=Db::table("cg_channel_types1")->where(["id"=>$yusuande[$i]["channel1"]])->value("title");
            $yusuande[$i]["pinpai"]=Db::table("pro_brands")->where(["id"=>$yusuande[$i]["pinpai"]])->value("brand_name");
            $yusuande[$i]["erjifeiyong"]=Db::table("cg_feiyongkemu2")->where(["id"=>$yusuande[$i]["erjifeiyong"]])->value("title");
            $yusuande[$i]["weiyong"]=round($yusuande[$i]["jine"]-$yusuande[$i]["ytongguo"],2);
            $yusuande[$i]["sjine"]=round($yusuande[$i]["sjine"],2);
        }
        if($flag2==1){
            $checkwt["ys"]=2;//未设定预算
            $wtd[] ="本申请中存在预算申请将超预算的情况";
        }else if($flag2==2){
            $checkwt["ys"]=3;//未设定预算
            $wtd[] ="本申请中存在预算申请已超预算的情况";
        }
        $this->assign("yusuande",$yusuande);
        //按照三级费用科目查询
        $sjfykm = db('cg_ti_list')->where('ti_id', $yw_id)->field('feetype')->group('feetype')->select();
        foreach($sjfykm as $k=>$v){
            $v['feetype_name'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');

            $v['sqje'] = db('cg_ti_list')->where(['ti_id'=> $yw_id,'feetype'=>$v['feetype']])->sum('pizhunhanshui');

            $sjfykm[$k] = $v;
        }
        $this->assign('sjfykm',$sjfykm);
        /**
         *问题点--end
         */
        $this->assign("checkwt",$checkwt);
        $this->assign("wtd",$wtd);
        $this->assign("info",$info);
        /*当年*/

        $this->dangnian($info['start'],$apply["jxs_id"]);
        return $this->fetch();
    }

    //当年经销商图标---参数时间戳,经销商
    public function dangnian($time,$jid){
        $now=$time;
        $cainian=Db::table("cg_cainian")->where("starttime<=$now and endtime>=$now")->field("id,title,starttime,endtime")->find();
        $nownian=$cainian["title"];
        $cid=$cainian["id"];
        $this->assign("nownian",$nownian);
        $cnqk=[];
        //当年目标
        $cnqk['tar']=Db::table("target_apply")->alias("t")->join("target_apply_detail td","td.apply_id=t.id")
            ->where("t.type_id=5 and t.state=7 and t.tag<>1 and t.is_actived=1 and t.is_deleted=0 and td.jingxiao={$jid} and td.cainian={$cainian["id"]}")->sum("feiyong");
        if(!$cnqk['tar'])
            $cnqk['tar']=0;
        else
            $cnqk['tar']=round($cnqk['tar'],2);
        $cnqk["fy"]=Db::table("bx_fy")->alias("b")
        ->where("fyDate like '{$nownian}%' and sdAgency_id=$jid")->sum("fyZheMoney");
        if(!$cnqk["fy"])
            $cnqk["fy"]=0;
        else
            $cnqk["fy"]=round($cnqk["fy"],2);
        if($cnqk['tar']>$cnqk["fy"]){
            $cnqk["tarbi"]=100;
            $cnqk["fybi"]=round($cnqk["fy"]/$cnqk["tar"]*100);
        }else if($cnqk['tar']<$cnqk["fy"]){
            $cnqk["fybi"]=100;
            $cnqk["tarbi"]=round($cnqk["tar"]/$cnqk["fy"]*100);
        }else{
            $cnqk["fybi"]=100;
            $cnqk["tarbi"]=100;
        }
        if($cnqk['tar']){
            $cnqk['tardacheng']=round($cnqk["fy"]/$cnqk["tar"]*100,2);
        }else
            $cnqk['tardacheng']=0;
        //经销商预算
        $cnqk["ys"]=db("yusuan")->alias("y")
        ->where(["y.jingxiao"=>$jid,"y.type"=>1,"y.cainian"=>$cid])->sum("y.jine");
        if(!$cnqk["ys"]){
            $cnqk["ys"]=0;
            $cnqk["ysbi"]=0;
            $cnqk["ysno"]=0;
            $cnqk["ysnobi"]=0;$cnqk['has']=0;
        }else{
            $cnqk['has']=db("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")
            ->where(["y.jingxiao"=>$jid,"y.type"=>1,"y.cainian"=>$cid,"yd.type"=>2])->sum("yd.jine");
            if(!$cnqk['has'])
                $cnqk['has']=0;
            else
                $cnqk['has']=round($cnqk['has'],2);
            $cnqk["ys"]=round($cnqk["ys"],2);
            $cnqk["ysno"]=$cnqk["ys"]-$cnqk['has'];
            if($cnqk["ysno"]>0){
                $cnqk["ysnobi"]=round($cnqk["ysno"]/$cnqk["ys"])*100;
                
            }else{
                $cnqk["ysnobi"]=0;
                
            }
            $cnqk["ysbi"]=100-$cnqk["ysnobi"];
        }
        //费用率
        $tmp=Db::table("cg_ti")->alias("ap")
        ->join("cg_ti_list apd", "apd.ti_id=ap.id")->where("ap.jxs_id=$jid and ap.status in(7,9) and ap.status2 is null")->field("apd.totalExpectedSales,apd.yjsjtrfy as hanshui,apd.fb_shijitourufeiyong,apd.fb_shijixiaoliang")->select();
        $cnqk["hs"]=0;$cnqk["xl"]=0; $cnqk["shs"]=0;$cnqk["sxl"]=0;
        for($i=0;$i<count($tmp);$i++){
            if($tmp[$i]["hanshui"]&&$tmp[$i]["totalExpectedSales"]){
                $cnqk["hs"]+=$tmp[$i]["hanshui"];
                $cnqk["xl"]+=$tmp[$i]["totalExpectedSales"];
            }
            if($tmp[$i]["fb_shijitourufeiyong"]&&$tmp[$i]["fb_shijixiaoliang"]){
                $cnqk["shs"]+=$tmp[$i]["fb_shijitourufeiyong"];
                $cnqk["sxl"]+=$tmp[$i]["fb_shijixiaoliang"];
            }
        }
        if($cnqk["hs"]&&$cnqk["xl"]){
            $cnqk["fyl"]=round($cnqk["hs"]/$cnqk["xl"]*100,2);
        }else{
            $cnqk["fyl"]=0;
        }
        if($cnqk["shs"]&&$cnqk["sxl"]){
            $cnqk["sfyl"]=round($cnqk["shs"]/$cnqk["sxl"]*100,2);
        }else{
            $cnqk["sfyl"]=0;
        }
        if($cnqk["sfyl"]>=$cnqk["fyl"]){
            $cnqk["cfyl"]=$cnqk["sfyl"]-$cnqk["fyl"];
        }else{
            $cnqk["cfyl"]=$cnqk["fyl"]-$cnqk["sfyl"];
        }
        $this->assign("cnqk",$cnqk);
    }
    public function formmatsave(){
        $request = Request::instance();$data = $request->post();
        //print_r($data);exit;
        $up["id"]=$data["did"];
        $up["pizhunweishui"]=$data["pizhunweishui"];
        $up["pizhunhanshui"]=$data["pizhunhanshui"];
        
        $up["yjsjtrfy"]=$data["pizhunhanshui"];
        
        $up["yujifeiyonglv"]=$data["yjfyl"];
        $up["yujiroi"]=$data["yjroi"];
        if(isset($data["isorno"]))
            $up["isOrNo"]=$data["isorno"];
        $ys=db("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where(["y.type"=>1,"yd.did"=>$data["did"]])->field("yd.id")->select();
        //print_r($ys);exit;
        Db::startTrans();
        try{
            db::table("cg_ti_list")->update($up);
            if($ys){
                $ysarr=[];
                for($i=0;$i<count($ys);$i++){
                    $ysarr[]=$ys[$i]["id"];
                }
                $ysstr=implode(',',$ysarr);
                db("yusuan_detail")->where("id in ($ysstr)")->delete();
                
            }
            if((float)$up["pizhunhanshui"]){
                $nys=$this->tidys($data["did"]);
                if($nys){
                    db("yusuan_detail")->insertAll($nys);
                }
            }
            
            //
            
        }catch (\Exception $e) {
            Db::rollBack();
            return json_encode(["msg"=>$e->getMessage(),"state"=>2]);
        }
        Db::commit();
        return json_encode(["msg"=>"","state"=>1]);
        
    }
    //常规促销费用申请-待阅
    public function formalbacklogdetail2(){
        $workId = $this->request->param('workId');
        $trackId = $this->request->param('trackId');
        $myId = $this->request->param('myId');
//yw_id
        $yw_id =db('cg_workflow')->where('id',$myId)->value('yw_id');
        $this->assign('yw_id',$yw_id);

        if($_POST){
            $type = $this->request->post('type');
            if($type==1){ //选定办理人
                $nodeId = $this->request->post('nodeId');
                $data = $this->request->post('data');
                $selectAuthor = $this->request->post('Author');
                $selectAuthorName = db('users t')->join('employee t2','t.employee_id=t2.id')->where('t.id',$selectAuthor)->value('t2.em_name');
                $data = json_decode($data);
                $data = $this->object_array($data);
                $xdjd = [];
                foreach($data['nextNodes'] as $k=>$v){
                        $v['isSelect'] = "true";
                        $data['nextNodes'][$k] = $v;
                        $xdjd = $v;
                }
                $actionData = [
                    'operate'=>'submit',
                    'operateClazz'=>'com.horizon.wf.action.ActionSubmit',
                    'operateText'=>'提 交',
                    'operateFlag'=>0,
                    'nextNodes'=>[
                        [
                            'nodeKey'=>$xdjd['nodeKey'],
                            'selectId'=>$xdjd['selectId'],
                            'selectName'=>$xdjd['selectName'],
                            'isSelect'=>$xdjd['isSelect'],
                            'authors'=>[
                                'Author'=>[
                                    'authorId'=>'Author',
                                    'selectAuthor'=>$selectAuthor,
                                    'selectAuthorName'=>$selectAuthorName,
                                ]
                            ],
                            'nodeId'=>$data['nextNodes'][0]['nodeId'],
                            'nodeName'=>$data['nextNodes'][0]['nodeName'],
                        ]
                    ],
                    "subFlows"=>null
                ];
                $param = [
                    'accessToken'=>session("accessToken"),
                    'workId'=>$workId,
                    'trackId'=>$trackId,
                    'nodeId'=>$nodeId,
                    'actionData'=>$actionData,
                    "comment"=>"",
                    "dataId"=>"",
                ];
                $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/action.wf',$param);

                $data = object_array($data);
                if($data['operateMsg']=='提交成功'){
                    $spyj = $this->request->post('spyj');
                    db('cg_workflow_spyj')->insert([
                        'spr_id'=>session('employee_id'),
                        'spr_name'=>db('employee')->where('id',session('employee_id'))->value('em_name'),
                        'spr_job'=>db('job t')->join('job_employee t2','t2.job_id=t.id')->where('t2.employee_id',session('employee_id'))->value('t.job_name'),
                        'wf_id'=>$myId,
                        'spyj'=>$spyj,
                        'spdz'=>$xdjd['nodeName'],
                        'spsj'=>date('Y-m-d H:i:s')
                    ]);
                    //$xdjd['nodeName']或者$data['nextNodes'][0]['nodeName'];
                    db('cg_ti')->where('id',$yw_id)->update(['status'=>$xdjd['nodeName']]);
                    $this->redirect('index');
                }else{
                    echo $data['operateMsg'];
                }
                die;
            }elseif($type==2){ //选定节点
                $data = $this->request->post('data');
                $nodeId = $this->request->post('node');
                $data = json_decode($data);
                $data = $this->object_array($data);
                $spyj = $this->request->post('spyj');
                $this->assign('spyj',$spyj);
                $xdjd = [];
                foreach($data['nextNodes'] as $k=>$v){
                    if($v['nodeId'] == $nodeId){
                        $v['isSelect'] = "true";
                        $data['nextNodes'][$k] = $v;
                        $xdjd = $v;
                    }
                }
                $nodeId = $data['nodeId'];

                $nextNodes = [[
                    'nodeKey'=>$xdjd['nodeKey'],
                    'selectId'=>$xdjd['selectId'],
                    'selectName'=>$xdjd['selectName'],
                    'isSelect'=>$xdjd['isSelect']
                ]];
                $actionData = [
                    'operate'=>'submit',
                    'operateClazz'=>'com.horizon.wf.action.ActionSubmit',
                    'operateText'=>'提 交',
                    'operateFlag'=>1,
                    'nextNodes'=>$nextNodes
                ];
                $param = [
                    'accessToken'=>session("accessToken"),
                    'workId'=>$workId,
                    'trackId'=>$trackId,
                    'nodeId'=>$nodeId,
                    'actionData'=>$actionData,
                ];echo '<pre>';print_r($param);
                $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/action.wf',$param);

                $data = object_array($data);
                $this->assign('data',$data);print_r($data);
                return $this->fetch('xzblr');
            }else{
                $nodeId = $this->request->post('nodeId');
                $spyj = $this->request->post('spyj');
                $this->assign('spyj',$spyj);
                $actionData = [
                    'operate'=>'submit',
                    'operateClazz'=>'com.horizon.wf.action.ActionSubmit',
                    'operateText'=>'提 交',
                    'operateFlag'=>1,
                ];
                $param = [
                    'accessToken'=>session("accessToken"),
                    'workId'=>$workId,
                    'trackId'=>$trackId,
                    'nodeId'=>$nodeId,
                    'actionData'=>$actionData,
                ];
                $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/action.wf',$param);

                $data = object_array($data);
                $this->assign('data',$data);
                if($data['operateMsg'] == '请从列表中选择节点'){
                    return $this->fetch('xzjd');
                }else{
                    return $this->fetch('xzblr');
                }
            }
            die;
        }
        //打开工作流
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['workId'] = $workId;
        $post_data['trackId'] = $trackId;
        $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/open.wf',$post_data);
        $data = object_array($data);
        $this->assign('data',$data);

        $info = db('cg_ti')->where('id',$yw_id)->find();
        $info['jxs_name'] = db('cg_jxs')->where('id',$info['jxs_id'])->value('title');
        $info['sqr'] = db('employee')->where('id',$info['cuser'])->value('em_name');
        $info['sqr_job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->where('t2.employee_id',$info['cuser'])->value('t.job_name');
        $info['zoning'] = db('cg_market_zoning t')->join('cg_jxs t2','t2.zoning=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['provice'] = db('cg_market_provice t')->join('cg_jxs t2','t2.provice=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['city'] = db('cg_market_city t')->join('cg_jxs t2','t2.city=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['jxs_type'] = db('cg_jxs_types t')->join('cg_jxs t2','t2.types=t.id')->where('t2.id',$info['jxs_id'])->value('t.title');
        $info['start'] = db('cg_ti_list')->where('ti_id',$yw_id)->value('start');
        $info['end'] = db('cg_ti_list')->where('ti_id',$yw_id)->value('end');

        if($info['productlat']==1){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'brand'=>['exp','is not null']])->value('brand');
            $info['pro_label'] = '品牌';
            $info['pro_name'] = db('pro_brands')->where('id',$brand_id)->value('brand_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->count('brand');
        }elseif($info['productlat']==2){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'category'=>['exp','is not null']])->value('category');
            $info['pro_label'] = '品类';
            $info['pro_name'] = db('pro_category')->where('id',$brand_id)->value('category_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->count('category');
        }elseif($info['productlat']==3){
            $info['pro_label'] = '系列';
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'series'=>['exp','is not null']])->value('series');
            $info['pro_name'] = db('pro_series')->where('id',$brand_id)->value('series_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->count('series');
        }elseif($info['productlat']==4){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'sku'=>['exp','is not null']])->value('sku');
            $info['pro_label'] = 'sku';
            $info['pro_name'] = db('pro_sku')->where('id',$brand_id)->value('sku_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->count('sku');
        }elseif($info['productlat']==5){
            $brand_id = db('cg_ti_list')->where(['ti_id'=>$yw_id,'product'=>['exp','is not null']])->value('product');
            $info['pro_label'] = '产品';
            $info['pro_name'] = db('pro_products')->where('id',$brand_id)->value('pro_name');
            $info['p_cnt'] = db('cg_ti_list')->where('ti_id',$yw_id)->count('product');
        }



        $apply = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti yuan", "ap.old=yuan.id", "LEFT")
            ->join("cg_ti next", "ap.new=next.id", "LEFT")
            ->join("ti_state s", "ap.status=s.id")
            ->join("employee ec", "ap.cuser=ec.id", "LEFT")
            ->join("job_employee je", "ec.id=je.employee_id", "LEFT")
            ->join("job j", "je.job_id=j.id", "LEFT")
            ->join("department_employee de", "ec.id=de.employee_id", "LEFT")
            ->join("department d", "de.department_id=d.id", "LEFT")
            ->join("cg_jxs jx", "ap.jxs_id=jx.id")
            ->join("cg_market_zoning jz", "jx.zoning=jz.id", "LEFT")
            ->join("cg_market_provice jp", "jx.provice=jp.id", "LEFT")
            ->join("cg_market_city jc", "jx.city=jc.id", "LEFT")
            ->where(["ap.id" => $yw_id, "de.index" => 1])
            ->field("ap.title,ap.sn as no,yuan.sn as yuanno,next.sn as nextno,yuan.id as yuanid,next.id as nextid,s.title as zhuangtai,ec.em_name as cname,j.job_name,d.de_name,ap.ctime as created_on,jx.title as jingxiao,jz.title as fenqu,jp.title as sheng,jc.title as shi,yuan.status2 as yuantag,ap.status2 as nowtag,ap.status2 as tag,ap.fb is_fankui,ap.status")
            ->find();
        $apply["created_on"] = date("Y-m-d", $apply["created_on"]);
        $this->assign("apply", $apply);
        $fb = Db::table("all_ti_feeback_list")->where(["apply_id" => $yw_id, "type" => 0, "is_deleted" => 0, "is_actived" => 1])->find();
        $hx = Db::table("cg_ti_hexiao")->alias("h")->join("cg_ti_hexiao_list hl", "hl.hx_id=h.id")->where("hl.ti_id=$yw_id and status not in (8)")->group("h.id")->field("h.sn")->select();
        $flagfb = 0;
        if ($fb)
            $flagfb = 1;
        $flaghx = 0;
        if ($hx)
            $flaghx = 1;
        $this->assign("fb", $fb);
        $this->assign("flagfb", $flagfb);
        $this->assign("hx", $hx);
        $this->assign("flaghx", $flaghx);
        $applynet = Db::table("cg_ti")->query("select apd.net_id,sum(apd.totalExpectedSales) as sellnums,sum(apd.bucha) as buchas,sum(apd.amount) as zonges,sum(apd.pizhunweishui) as pifuzonges,sum(fb_shijiweishui) as fankuijines,sum(apd.pizhunhanshui) as hanshuis,sum(apd.fb_shijitourufeiyong) as fankuihanshuis,sum(apd.now_price*p.box_num*apd.totalExpectedSales) as xiaoshoues,sum(fb_shijixiaoliang) as fannums,sum(apd.now_price*p.box_num*apd.fb_shijixiaoliang) as fanxiaoshoues,(sum(fb_shijixiaoliang)/sum(apd.totalExpectedSales)*100) as dachenglv,sum(apd.hx_yihexiao) as hexiaos from cg_ti as ap inner join cg_ti_list as apd on apd.ti_id=ap.id inner join pro_products as p on apd.product=p.id where ap.id=$yw_id  group by apd.net_id");
        $this->assign("applynet", $applynet);
        $net_num = count($applynet);
        $this->assign("net_num", $net_num);

        $applyde = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_ti_list yuanapd", "apd.refer_id=yuanapd.id", "LEFT")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")
            ->join("cg_system s", "n.system_id=s.id", "LEFT")
            ->join("pro_products p", "apd.product=p.id")
            ->join("pro_sku sk", "p.sku_id=sk.id")
            ->join("pro_series ps", "sk.series_id=ps.id")
            ->join("pro_price pp", "pp.pid=p.id")
            ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")
            ->join("cg_paymethod cp", "apd.paymethod=cp.id")
            ->join("cg_fijiru cf", "apd.project=cf.id")
            ->join("cg_fijiruzd fj", "apd.jrbm=fj.id")->join("department d", "fj.title=d.id")
            ->where(["ap.id" => $yw_id])->order("apd.net_id,apd.product")
            ->field("ap.sn as no,apd.sn as detail_no,apd.net_id,apd.id as did,apd.is_bu,n.title as net,s.title as xitong,ps.series_name,p.pro_name,apd.start as start_time,apd.end as end_time,apd.expCanTime as  hexiao_time,apd.totalExpectedSales as sell_num,apd.bucha,p.unit,p.box_num,pp.factory,apd.yuan_price,apd.now_price,apd.wangdian_price,apd.lingshou_price,apd.huodong_price,f3.title as feiyong3,apd.amount as zonge,(apd.pizhunhanshui) as hanshui,apd.brief as beizhu,apd.head as fuzeren,cp.title as zffs,cf.title as jrfa,(apd.now_price*p.box_num*apd.totalExpectedSales) as xiaoshoue,apd.feiyongmiaoshu as remark,d.de_name,apd.shuilv,apd.isVAT as dikou,apd.zhejia,apd.hx_yihexiao as hexiao,apd.paymethod as zfid,apd.status as tag,yuanapd.start  as yuanstart,yuanapd.end as yuanend,yuanapd.expCanTime as yuanhexiao,apd.ydreason,apd.cancel_reason,apd.fb_shijixiaoliang as fankuinum,(apd.now_price*p.box_num*apd.fb_shijixiaoliang) as shijixiaoshoue,(apd.fb_shijixiaoliang/apd.totalExpectedSales)*100 as xiaoliang,(apd.wangdian_price*apd.zhejia/100) as zj,(apd.wangdian_price-apd.wangdian_price*apd.zhejia/100) as wangcuxiao,(apd.wangdian_price*apd.zhejia/100)*p.box_num*apd.fb_shijixiaoliang as zjzj,yuanapd.pizhunweishui  as yuanzonge,apd.pizhunweishui as  pifuzonge,apd.fb_shijiweishui as fankuijine,apd.fb_shijitourufeiyong as fankuihanshui")
            ->select();

        for ($i = 0; $i < count($applyde); $i++) {
            $applyde[$i]["start_time"] = date("Y-m-d", $applyde[$i]["start_time"]);
            $applyde[$i]["end_time"] = date("Y-m-d", $applyde[$i]["end_time"]);
            $applyde[$i]["hexiao_time"] = date("Y-m-d", $applyde[$i]["hexiao_time"]);
            if ($applyde[$i]["yuanstart"])
                $applyde[$i]["yuanstart"] = date("Y-m-d", $applyde[$i]["yuanstart"]);
            if ($applyde[$i]["yuanend"])
                $applyde[$i]["yuanend"] = date("Y-m-d", $applyde[$i]["yuanend"]);
            if ($applyde[$i]["yuanhexiao"])
                $applyde[$i]["yuanhexiao"] = date("Y-m-d", $applyde[$i]["yuanhexiao"]);
        }
        //print_r($applyde);
        $this->assign("applyde", $applyde);

        //费用支付方式
        $fipay = db('cg_paymethod')->field('id,title')->select();
        $this->assign('fipay', $fipay);
        $this->assign("aid", $yw_id);

        //费用类型
        $info['fylx'] = Db::query('select count(*) cnt from (select feetype from cg_ti_list where ti_id='.$yw_id.' group by feetype) t')[0]['cnt'];
        $info['fylx_name'] = db('cg_ti_list t')->join('cg_feiyongkemu3 t2','t2.id=t.feetype')->where('ti_id',$yw_id)->value('t2.title');
        $info['fye'] = round(db('cg_ti_list')->where(['ti_id'=>$yw_id])->sum('yjsjtrfy'),2);
        $info['xl'] = round(db('cg_ti_list')->where(['ti_id'=>$yw_id])->sum('totalExpectedSales'),2);
        $info['fyl'] = round($info['fye']/$info['xl']*100,2);
        $gs = db('cg_ti_list')->where(['ti_id'=>$yw_id])->count();
        $yujiroi = db('cg_ti_list')->where(['ti_id'=>$yw_id])->sum('yujiroi');
        $info['roi'] = round($yujiroi/$gs,2);

        //查看活动是否重复--判断是否存在费用类型相同收款方也相同的情况
        /*$cnt1 = Db::query('SELECT count(*) cnt from (SELECT gys,count(gys) AS count FROM cg_ti_list where ti_id='.$yw_id.' and gys is not null GROUP BY feetype,payee HAVING count > 1) t');
        $cnt1 = $cnt1[0]['cnt'];

        $info['iscf'] =$cnt1;*/

        $this->assign('info',$info);

        /**
         *问题点--start
         */
        $wtd = [];
        //公司建议的TI活动最高费用率值
        $feiYongLv = db('system_param')->where(['t'=>0,'k'=>'feiYongLv'])->value('v');
        if($info['fyl']>$feiYongLv){
            $wtd[] = '本申请单费用率不符合公司规定，公司规定为：'.$feiYongLv.'%';
        }
        //公司建议的TI活动ROI合格值
        $minRoi = db('system_param')->where(['t'=>0,'k'=>'minRoi'])->value('v');
        if($info['roi']<$minRoi){
            $wtd[] = '本申请单ROI不符合公司规定，公司规定合格值为：'.$minRoi.'%';
        }
        //公司建议的TI活动ROI较优值
        $maxRoi = db('system_param')->where(['t'=>0,'k'=>'maxRoi'])->value('v');
        /**
         *问题点--end
         */

        /**
         * 活动列表--start
         */
        $ti_list = db('cg_ti_list')->where('ti_id',$yw_id)->field('start,end,feetype,product,brand,category,series,sku,yjsjtrfy,totalExpectedSales,paymethod')->select();
        foreach($ti_list as $k=>$v){
            $v['feetype_name'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
            if($v['product'])
                $v['product_name'] = db('pro_products')->where('id',$v['product'])->value('pro_name');
            elseif($v['brand'])
                $v['product_name'] = db('pro_brands')->where('id',$v['brand'])->value('brand_name');
            elseif($v['category'])
                $v['product_name'] = db('pro_category')->where('id',$v['category'])->value('category_name');
            elseif($v['series'])
                $v['product_name'] = db('pro_series')->where('id',$v['series'])->value('series_name');
            elseif($v['sku'])
                $v['product_name'] = db('pro_sku')->where('id',$v['sku'])->value('sku_name');
            $v['yjfyl'] = round($v['yjsjtrfy']/$v['totalExpectedSales']*100,2);
            $v['zffs'] = db('cg_paymethod')->where('id',$v['paymethod'])->value('title');
            $ti_list[$k] = $v;
        }
        $this->assign('ti_list',$ti_list);
        /**
         * 活动列表--end
         */

        //本次申请已耗时
        $time = time()-$info['ctime'];
        $bcsqhs = $this->vtime($time);
        $this->assign('bcsqhs',$bcsqhs);

        //获取操作记录
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['workId'] = $workId;
        $czjl = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/history.wf',$post_data);
        $czjl = object_array($czjl);
//        echo "<pre>";print_r($czjl);
        foreach($czjl as $k=>$v){
            //查询审批意见
            $wf_id = 0;
//            $v['spyj'] = db('cg_workflow_spyj')->where(['wf_id'=>$wf_id,'spr_id']);
        }
        $this->assign('czjl',$czjl);

        //查询附件
        $attachs = db('cg_workflow_spyj')->where('wf_id',$myId)->column('attach');
        if($attachs){
            $attach = [];
            foreach($attachs as $item){
                if($item){
                    $item = unserialize($item);
                    foreach($item as $k=>$v){
                        $temp = Db::table('annex')->where(array('id'=>$v))->find();
                        $temp['path'] = '/uploads/'.$temp['path'];
                        $item[$k] = $temp;
                    }
                    $attach = array_merge($attach,$item);
                }
            }

            $this->assign('attach',$attach);

        }
        return $this->fetch();
    }

    //查看非常规申请明细
    public function noformalmx(){
        $id = $this->request->param('id');
        $data = db('cg_ti')->where('id',$id)->find();
        $data['zoning'] = db('cg_jxs t')->join('cg_market_zoning t2','t2.id=t.zoning')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['provice'] = db('cg_jxs t')->join('cg_market_provice t2','t2.id=t.provice')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['city'] = db('cg_jxs t')->join('cg_market_city t2','t2.id=t.city')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['cusername'] = db('employee')->where('id',$data['cuser'])->value('em_name');

        switch ($data['status']){
            case 2:
                $data['status_title'] = '已打回';
                break;
            case 3:
                $data['status_title'] = '区域领导审批';
                break;
            case 4:
                $data['status_title'] = '拆分人审批';
                break;
            case 5:
                $data['status_title'] = '集团领导审批';
                break;
            case 6:
                $data['status_title'] = '抄送';
                break;
            case 7:
                $data['status_title'] = '已归档';
                break;
            case 8:
                $data['status_title'] = '已作废';
                break;
            case 9:
                $data['status_title'] = '已否决';
                break;
            default:
                $data['status_title'] = '草稿';
        }
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $data['job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->join('employee t3','t3.id=t2.employee_id')->where('t3.id',$data['cuser'])->value('t.job_name');

        //查询明细列表
        if($data['arealat']==1){
            $list = db('cg_ti_list')->where('ti_id',$id)->group('jxs_id')->field('jxs_id')->select();
            foreach($list as $k=>$v){
                $list[$k]['_child'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->select();
                $list[$k]['st_amount'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('amount');//小计-未税费用金额
                $list[$k]['st_pw'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('pizhunweishui');//小计-未税费用金额
                $list[$k]['st_hanshui'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('hanshui');//小计-含税费用金额
                $list[$k]['st_shijitourufeiyong'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('yjsjtrfy');//小计-含税税费用金额
                $list[$k]['st_shijitourufeiyong'] = round($list[$k]['st_shijitourufeiyong'],2);
                $list[$k]['st_yujixiaoliang'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('totalExpectedSales');//小计-预计销量
                $list[$k]['st_yujixiaoliang'] = round($list[$k]['st_yujixiaoliang'],2);
                $list[$k]['st_yujifeiyonglv'] = $list[$k]['st_yujixiaoliang']?$list[$k]['st_hanshui']/$list[$k]['st_yujixiaoliang']*100:0;//小计-预计费用率
                $list[$k]['st_yujifeiyonglv'] = round($list[$k]['st_yujifeiyonglv'],2);
                $list[$k]['st_2srjizhun'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('2srjizhun');//小计-2sr基准销量
                $list[$k]['st_jizhunxiaoliang'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('totalBenchmarkSales');//小计-基准销量
                $list[$k]['st_jizhunxiaoliang'] = round($list[$k]['st_jizhunxiaoliang'],2);
                $list[$k]['st_yujiroi'] = round(db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('yujiroi'),2);//小计-预计rio
                $list[$k]['st_yihexiao'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('hx_yihexiao');//小计-已核销金额
                $list[$k]['st_shijixiaoliang'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('shijixiaoliang');//小计-实际销量
                $list[$k]['st_xiaoshoudachenglv'] = $list[$k]['st_yujixiaoliang']?$list[$k]['st_shijixiaoliang']/$list[$k]['st_yujixiaoliang']*100:0;
            }
        }else{
            $list = db('cg_ti_list')->where('ti_id',$id)->group('net_id')->field('net_id')->select();
            foreach($list as $k=>$v){
                $list[$k]['_child'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->select();
                $list[$k]['st_amount'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('amount');//小计-未税费用金额
                $list[$k]['st_pw'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('pizhunweishui');//小计-未税费用金额
                $list[$k]['st_hanshui'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('hanshui');//小计-含税费用金额
                $list[$k]['st_shijitourufeiyong'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('yjsjtrfy');//小计-实际投入费用
                $list[$k]['st_shijitourufeiyong'] = round($list[$k]['st_shijitourufeiyong'],2);
                $list[$k]['st_yujixiaoliang'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('totalExpectedSales');//小计-预计销量
                $list[$k]['st_yujixiaoliang'] = round($list[$k]['st_yujixiaoliang'],2);
                $list[$k]['st_yujifeiyonglv'] = $list[$k]['st_yujixiaoliang']?$list[$k]['st_hanshui']/$list[$k]['st_yujixiaoliang']*100:0;//小计-预计费用率
                $list[$k]['st_yujifeiyonglv'] = round($list[$k]['st_yujifeiyonglv'],2);
                $list[$k]['st_2srjizhun'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('2srjizhun');//小计-2sr基准销量
                $list[$k]['st_jizhunxiaoliang'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('totalBenchmarkSales');//小计-基准销量
                $list[$k]['st_jizhunxiaoliang'] = round($list[$k]['st_jizhunxiaoliang'],2);
                $list[$k]['st_yujiroi'] = round(db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('yujiroi'),2);//小计-预计rio
                $list[$k]['st_yihexiao'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('hx_yihexiao');//小计-已核销
                $list[$k]['st_shijixiaoliang'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('shijixiaoliang');//小计-实际销量
                $list[$k]['st_xiaoshoudachenglv'] = $list[$k]['st_yujixiaoliang']?$list[$k]['st_shijixiaoliang']/$list[$k]['st_yujixiaoliang']*100:0;
            }
        }

        foreach($list as $k=>$v){
            foreach($v['_child'] as $k1=>$v1){
                if($v1['status']==1){ //异动
                    $start = db('cg_ti_list')->where('id',$v1['refer_id'])->value('start');
                    $end = db('cg_ti_list')->where('id',$v1['refer_id'])->value('end');
                    if($start != $v1['start']&&$end!=$v1['end']){
                        $v['_child'][$k1]['start'] = $start;
                        $v['_child'][$k1]['end'] = $end;
                        $v['_child'][$k1]['ydstart'] = $v1['start'];
                        $v['_child'][$k1]['ydend'] = $v1['end'];
                    }
                }
                $v['_child'][$k1]['eauser_title'] = db('employee')->where('id',$v1['eauser'])->value('em_name');
                if($v1['jxs_id']){
                    $v['_child'][$k1]['jxs_title'] = db('cg_jxs')->where('id',$v1['jxs_id'])->value('title');
                }else{
                    $v['_child'][$k1]['jxs_id'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v1['net_id'])->value('t.jxs');
                    $v['_child'][$k1]['jxs_title'] = db('cg_jxs')->where('id',$v['_child'][$k1]['jxs_id'])->value('title');
                }
                $v['_child'][$k1]['feetype'] = db('cg_feiyongkemu3')->where('id',$v1['feetype'])->value('title');
                $v['_child'][$k1]['paymethod_title'] = db('cg_paymethod')->where('id',$v1['paymethod'])->value('title');

                $v['_child'][$k1]['jrbm_puser_name'] = db('cg_fijiruzd t')
                    ->join('employee t2','t2.id=t.puser')
                    ->where('t.title',$v1['jrbm'])
                    ->value('t2.em_name');//费用计入部门修改人
                $v['_child'][$k1]['jrbm'] = db('department t')
                    ->join('cg_fijiruzd t2','t2.title = t.id')
                    ->where('t2.id',$v1['jrbm'])
                    ->value('t.de_name');

                $v['_child'][$k1]['jrbm_dp'] = db('cg_fijiru')->where('id',$v1['project'])->value('title');
                $v['_child'][$k1]['jrbm_dp_puser'] = db('cg_fijiru t')->join('employee t2','t2.id=t.puser')->where('t.id',$v1['project'])->value('t2.em_name');
                $v['_child'][$k1]['brand'] = db('pro_brands')->where('id',$v1['brand'])->value('brand_name');
                if($v1['net_id'])
                    $v['_child'][$k1]['net_title'] = db('cg_net')->where('id',$v1['net_id'])->value('title');
                $v['_child'][$k1]['productlatval'] = $this->productlatval($v1);
                //$v['_child'][$k1]['yujifeiyonglv'] = $v1['totalExpectedSales']?round($v1['fb_shijitourufeiyong']/$v1['hanshui'],2)*100:0;
                $v['_child'][$k1]['xiaoshoudachenglv'] = $v1['totalExpectedSales']?round($v1['fb_shijixiaoliang']/$v1['totalExpectedSales'],2)*100:0;
                $v['_child'][$k1]['gys_name'] = db('gys')->where('id',$v1['gys'])->value('gys_name');
            }
            $list[$k] = $v;
        }

        $data['list'] = $list;

        //查询供应商数量
        $data['net_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('net_id is not null')->group('net_id')->count();
        $data['brand_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('brand is not null')->group('brand')->count();
        $data['category_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('category is not null')->group('category')->count();
        $data['series_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('series is not null')->group('series')->count();
        $data['sku_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('sku is not null')->group('sku')->count();
        $data['product_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('product is not null')->group('product')->count();
        $data['feetype_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('feetype is not null')->group('feetype')->count();
        $data['arealat_title'] = $data['arealat']==1?'经销商名称':'网点名称';
        if($data['productlat']==1) { //产品纬度
            $data['product_title'] = '品牌';
        }elseif($data['productlat']==2) {
            $data['product_title'] = '品类';
        }elseif($data['productlat']==3) {
            $data['product_title'] = '系列';
        }elseif($data['productlat']==4) {
            $data['product_title'] = 'sku';
        }elseif($data['productlat']==5) {
            $data['product_title'] = '产品';
        }
        $data['amounts'] = db('cg_ti_list')->where('ti_id',$id)->sum('amount');
        $data['pw'] = db('cg_ti_list')->where('ti_id',$id)->sum('pizhunweishui');
        $data['hanshui']  = db('cg_ti_list')->where(['ti_id'=>$id])->sum('hanshui');//总计-含税费用金额
        $data['shijitourufeiyong']  = db('cg_ti_list')->where(['ti_id'=>$id])->sum('yjsjtrfy');//总计-实际投入费用
        $data['shijitourufeiyong'] = round($data['shijitourufeiyong'],2);
        $data['yujixiaoliang'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('totalExpectedSales');//总计-预计销量
        $data['yujixiaoliang'] = round($data['yujixiaoliang'],2);
        $data['yujifeiyonglv'] = $data['yujixiaoliang']?$data['hanshui']/$data['yujixiaoliang']*100:0;//总计-预计费用率
        $data['yujifeiyonglv'] = round($data['yujifeiyonglv'],2);
        $data['2srjizhun'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('2srjizhun');//总计-2sr基准销量
        $data['jizhunxiaoliang'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('totalBenchmarkSales');//总计-基准销量
        $data['jizhunxiaoliang'] = round($data['jizhunxiaoliang'],2);
        $data['yujiroi'] = round(db('cg_ti_list')->where(['ti_id'=>$id])->sum('yujiroi'),2);//总计-预计rio
        $data['yihexiao'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('hx_yihexiao');//总计-已核销
        $data['shijixiaoliang'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('shijixiaoliang');//总计-实际销量
        $data['xiaoshoudachenglv'] = $data['yujixiaoliang']?$data['shijixiaoliang']/$data['yujixiaoliang']*100:0;

        $data['yhx'] = db('cg_ti_hexiao_list t')
            ->join('cg_ti_list t2','t2.id=t.list_id')
            ->where('t2.ti_id',$id)->count();
//        echo db('cg_ti_list')->getLastSql();
        $this->assign('data',$data);

       $logs=$this->getlog(3,$id);
       $this->assign("logs",$logs);

        //按照三级费用科目查询
        $sjfykm = db('cg_ti_list')->where('ti_id',$id)->field('feetype')->group('feetype')->select();
        foreach($sjfykm as $k=>$v){
            $v['feetype_name'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
            $v['jxss'] = 1;
            $v['pps'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->sum('brand');
            $v['sqje'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->sum('hanshui');
            $sjfykm[$k] = $v;
        }
        $this->assign('sjfykm',$sjfykm);

        $export = $this->request->get('export');
        if($export){

            //根据经销商查询分区省份和城市
            $city = db('cg_jxs t')->join('cg_market_city t2','t.city=t2.id')->where('t.id',$data['jxs_id'])->value('t2.title');
            $provice = db('cg_jxs t')->join('cg_market_provice t2','t.provice=t2.id')->where('t.id',$data['jxs_id'])->value('t2.title');
            $zoning = db('cg_jxs t')->join('cg_market_zoning t2','t.zoning=t2.id')->where('t.id',$data['jxs_id'])->value('t2.title');
            $this->assign([
                'city'=>$city,
                'provice'=>$provice,
                'zoning'=>$zoning,
            ]);

            ob_end_clean();
            ob_start();

            header('Content-Type : application/vnd.ms-excel');
            header('Content-Disposition:attachment;filename="'.iconv('utf-8','gbk',$data['sn'].'-'.date("Y年m月j日")).'.xls"');
            return $this->fetch('view_export');
        }else{
            //查询核销编号
            $hxsn = db('cg_ti_hexiao t')
                ->join('cg_ti_hexiao_list t2','t2.hx_id=t.id')
                ->join('cg_ti_list t3','t3.id=t2.list_id')
                ->where('t3.ti_id',$id)
                ->field('t.id,t.sn')
                ->select();
            $this->assign('hxsn',$hxsn);
            //查询反馈编号
            $fbsn = db('all_ti_feeback_list t')
                ->join('cg_ti t2','t2.id=t.apply_id')
                ->where(['type'=>1,'t2.id'=>$id])
                ->field('t.id,t.no')
                ->find();
            $this->assign('fbsn',$fbsn);

            //查询用户名和密码
            $login_name = db('users')->where('id',session('login_id'))->value('login_name');
            $login_pwd = db('users')->where('id',session('login_id'))->value('login_pwd');
            $this->assign('login_name',$login_name);
            $this->assign('login_pwd',$login_pwd);

            return $this->fetch();
        }
    }

    //查看非常规申请明细-待阅
    public function noformalmx2(){
        $id = $this->request->param('id');
        $data = db('cg_ti')->where('id',$id)->find();
        $data['zoning'] = db('cg_jxs t')->join('cg_market_zoning t2','t2.id=t.zoning')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['provice'] = db('cg_jxs t')->join('cg_market_provice t2','t2.id=t.provice')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['city'] = db('cg_jxs t')->join('cg_market_city t2','t2.id=t.city')->where('t.id',$data['jxs_id'])->value('t2.title');
        $data['cusername'] = db('employee')->where('id',$data['cuser'])->value('em_name');

        switch ($data['status']){
            case 2:
                $data['status_title'] = '已打回';
                break;
            case 3:
                $data['status_title'] = '区域领导审批';
                break;
            case 4:
                $data['status_title'] = '拆分人审批';
                break;
            case 5:
                $data['status_title'] = '集团领导审批';
                break;
            case 6:
                $data['status_title'] = '抄送';
                break;
            case 7:
                $data['status_title'] = '已归档';
                break;
            case 8:
                $data['status_title'] = '已作废';
                break;
            case 9:
                $data['status_title'] = '已否决';
                break;
            default:
                $data['status_title'] = '草稿';
        }
        $data['jxs_title'] = db('cg_jxs')->where('id',$data['jxs_id'])->value('title');
        $data['job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->join('employee t3','t3.id=t2.employee_id')->where('t3.id',$data['cuser'])->value('t.job_name');

        //查询明细列表
        if($data['arealat']==1){
            $list = db('cg_ti_list')->where('ti_id',$id)->group('jxs_id')->field('jxs_id')->select();
            foreach($list as $k=>$v){
                $list[$k]['_child'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->select();
                $list[$k]['st_amount'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('amount');//小计-未税费用金额
                $list[$k]['st_hanshui'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('hanshui');//小计-含税费用金额
                $list[$k]['st_shijitourufeiyong'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('fb_shijitourufeiyong');//小计-含税税费用金额
                $list[$k]['st_shijitourufeiyong'] = round($list[$k]['st_shijitourufeiyong'],2);
                $list[$k]['st_yujixiaoliang'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('totalExpectedSales');//小计-预计销量
                $list[$k]['st_yujixiaoliang'] = round($list[$k]['st_yujixiaoliang'],2);
                $list[$k]['st_yujifeiyonglv'] = $list[$k]['st_hanshui']/$list[$k]['st_yujixiaoliang'];//小计-预计费用率
                $list[$k]['st_yujifeiyonglv'] = round($list[$k]['st_yujifeiyonglv'],2);
                $list[$k]['st_2srjizhun'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('2srjizhun');//小计-2sr基准销量
                $list[$k]['st_jizhunxiaoliang'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('totalBenchmarkSales');//小计-基准销量
                $list[$k]['st_jizhunxiaoliang'] = round($list[$k]['st_jizhunxiaoliang'],2);
                $list[$k]['st_yujiroi'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('yujiroi');//小计-预计rio
                $list[$k]['st_yihexiao'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('hx_yihexiao');//小计-已核销金额
                $list[$k]['st_shijixiaoliang'] = db('cg_ti_list')->where(['jxs_id'=>$v['jxs_id'],'ti_id'=>$id])->sum('shijixiaoliang');//小计-实际销量
                $list[$k]['st_xiaoshoudachenglv'] = $list[$k]['st_yujixiaoliang']?$list[$k]['st_shijixiaoliang']/$list[$k]['st_yujixiaoliang']*100:0;
            }
        }else{
            $list = db('cg_ti_list')->where('ti_id',$id)->group('net_id')->field('net_id')->select();
            foreach($list as $k=>$v){
                $list[$k]['_child'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->select();
                $list[$k]['st_amount'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('amount');//小计-未税费用金额
                $list[$k]['st_hanshui'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('hanshui');//小计-含税费用金额
                $list[$k]['st_shijitourufeiyong'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('fb_shijitourufeiyong');//小计-实际投入费用
                $list[$k]['st_shijitourufeiyong'] = round($list[$k]['st_shijitourufeiyong'],2);
                $list[$k]['st_yujixiaoliang'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('totalExpectedSales');//小计-预计销量
                $list[$k]['st_yujixiaoliang'] = round($list[$k]['st_yujixiaoliang'],2);
                $list[$k]['st_yujifeiyonglv'] = $list[$k]['st_yujixiaoliang']?$list[$k]['st_hanshui']/$list[$k]['st_yujixiaoliang']*100:0;//小计-预计费用率
                $list[$k]['st_yujifeiyonglv'] = round($list[$k]['st_yujifeiyonglv'],2);
                $list[$k]['st_2srjizhun'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('2srjizhun');//小计-2sr基准销量
                $list[$k]['st_jizhunxiaoliang'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('totalBenchmarkSales');//小计-基准销量
                $list[$k]['st_jizhunxiaoliang'] = round($list[$k]['st_jizhunxiaoliang'],2);
                $list[$k]['st_yujiroi'] = round(db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('yujiroi'),2);//小计-预计rio
                $list[$k]['st_yihexiao'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('hx_yihexiao');//小计-已核销
                $list[$k]['st_shijixiaoliang'] = db('cg_ti_list')->where(['net_id'=>$v['net_id'],'ti_id'=>$id])->sum('shijixiaoliang');//小计-实际销量
                $list[$k]['st_xiaoshoudachenglv'] = $list[$k]['st_yujixiaoliang']?$list[$k]['st_shijixiaoliang']/$list[$k]['st_yujixiaoliang']*100:0;
            }
        }

        foreach($list as $k=>$v){
            foreach($v['_child'] as $k1=>$v1){
                if($v1['status']==1){ //异动
                    $start = db('cg_ti_list')->where('id',$v1['refer_id'])->value('start');
                    $end = db('cg_ti_list')->where('id',$v1['refer_id'])->value('end');
                    if($start != $v1['start']&&$end!=$v1['end']){
                        $v['_child'][$k1]['start'] = $start;
                        $v['_child'][$k1]['end'] = $end;
                        $v['_child'][$k1]['ydstart'] = $v1['start'];
                        $v['_child'][$k1]['ydend'] = $v1['end'];
                    }
                }
                $v['_child'][$k1]['eauser_title'] = db('employee')->where('id',$v1['eauser'])->value('em_name');
                if($v1['jxs_id']){
                    $v['_child'][$k1]['jxs_title'] = db('cg_jxs')->where('id',$v1['jxs_id'])->value('title');
                }else{
                    $v['_child'][$k1]['jxs_id'] = db('cg_system t')->join('cg_net t2','t2.system_id=t.id')->where('t2.id',$v1['net_id'])->value('t.jxs');
                    $v['_child'][$k1]['jxs_title'] = db('cg_jxs')->where('id',$v['_child'][$k1]['jxs_id'])->value('title');
                }
                $v['_child'][$k1]['feetype'] = db('cg_feiyongkemu3')->where('id',$v1['feetype'])->value('title');
                $v['_child'][$k1]['paymethod_title'] = db('cg_paymethod')->where('id',$v1['paymethod'])->value('title');

                $v['_child'][$k1]['jrbm_puser_name'] = db('cg_fijiruzd t')
                    ->join('employee t2','t2.id=t.puser')
                    ->where('t.title',$v1['jrbm'])
                    ->value('t2.em_name');//费用计入部门修改人
                $v['_child'][$k1]['jrbm'] = db('department t')
                    ->join('cg_fijiruzd t2','t2.title = t.id')
                    ->where('t2.id',$v1['jrbm'])
                    ->value('t.de_name');

                $v['_child'][$k1]['jrbm_dp'] = db('cg_fijiru')->where('id',$v1['project'])->value('title');
                $v['_child'][$k1]['jrbm_dp_puser'] = db('cg_fijiru t')->join('employee t2','t2.id=t.puser')->where('t.id',$v1['project'])->value('t2.em_name');
                $v['_child'][$k1]['brand'] = db('pro_brands')->where('id',$v1['brand'])->value('brand_name');
                if($v1['net_id'])
                    $v['_child'][$k1]['net_title'] = db('cg_net')->where('id',$v1['net_id'])->value('title');
                $v['_child'][$k1]['productlatval'] = $this->productlatval($v1);
                $v['_child'][$k1]['yujifeiyonglv'] = $v1['totalExpectedSales']?round($v1['fb_shijitourufeiyong']/$v1['hanshui'],2)*100:0;
                $v['_child'][$k1]['xiaoshoudachenglv'] = $v1['totalExpectedSales']?round($v1['fb_shijixiaoliang']/$v1['totalExpectedSales'],2)*100:0;
                $v['_child'][$k1]['gys_name'] = db('gys')->where('id',$v1['gys'])->value('gys_name');
            }
            $list[$k] = $v;
        }

        $data['list'] = $list;

        //查询供应商数量
        $data['net_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('net_id is not null')->group('net_id')->count();
        $data['brand_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('brand is not null')->group('brand')->count();
        $data['category_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('category is not null')->group('category')->count();
        $data['series_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('series is not null')->group('series')->count();
        $data['sku_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('sku is not null')->group('sku')->count();
        $data['product_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('product is not null')->group('product')->count();
        $data['feetype_cnt'] = db('cg_ti_list')->where('ti_id',$id)->where('feetype is not null')->group('feetype')->count();
        $data['arealat_title'] = $data['arealat']==1?'经销商名称':'网点名称';
        if($data['productlat']==1) { //产品纬度
            $data['product_title'] = '品牌';
        }elseif($data['productlat']==2) {
            $data['product_title'] = '品类';
        }elseif($data['productlat']==3) {
            $data['product_title'] = '系列';
        }elseif($data['productlat']==4) {
            $data['product_title'] = 'sku';
        }elseif($data['productlat']==5) {
            $data['product_title'] = '产品';
        }
        $data['amounts'] = db('cg_ti_list')->where('ti_id',$id)->sum('amount');
        $data['hanshui']  = db('cg_ti_list')->where(['ti_id'=>$id])->sum('hanshui');//总计-含税费用金额
        $data['shijitourufeiyong']  = db('cg_ti_list')->where(['ti_id'=>$id])->sum('fb_shijitourufeiyong');//总计-实际投入费用
        $data['shijitourufeiyong'] = round($data['shijitourufeiyong'],2);
        $data['yujixiaoliang'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('totalExpectedSales');//总计-预计销量
        $data['yujixiaoliang'] = round($data['yujixiaoliang'],2);
        $data['yujifeiyonglv'] = $data['yujixiaoliang']?$data['hanshui']/$data['yujixiaoliang']*100:0;//总计-预计费用率
        $data['yujifeiyonglv'] = round($data['yujifeiyonglv'],2);
        $data['2srjizhun'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('2srjizhun');//总计-2sr基准销量
        $data['jizhunxiaoliang'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('totalBenchmarkSales');//总计-基准销量
        $data['jizhunxiaoliang'] = round($data['jizhunxiaoliang'],2);
        $data['yujiroi'] = round(db('cg_ti_list')->where(['ti_id'=>$id])->sum('yujiroi'),2);//总计-预计rio
        $data['yihexiao'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('hx_yihexiao');//总计-已核销
        $data['shijixiaoliang'] = db('cg_ti_list')->where(['ti_id'=>$id])->sum('shijixiaoliang');//总计-实际销量
        $data['xiaoshoudachenglv'] = $data['yujixiaoliang']?$data['shijixiaoliang']/$data['yujixiaoliang']*100:0;

        $data['yhx'] = db('cg_ti_hexiao_list t')
            ->join('cg_ti_list t2','t2.id=t.list_id')
            ->where('t2.ti_id',$id)->count();
//        echo db('cg_ti_list')->getLastSql();
        $this->assign('data',$data);

        //查询审批意见
        $workId = db('cg_workflow')->where(['ywlx'=>2,'yw_id'=>$id])->value('workId');
        //获取操作记录
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['workId'] = $workId;
        $spyj = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/history.wf',$post_data);
        $spyj = object_array($spyj);
        $this->assign('spyj',$spyj);

        //按照三级费用科目查询
        $sjfykm = db('cg_ti_list')->where('ti_id',$id)->field('feetype')->group('feetype')->select();
        foreach($sjfykm as $k=>$v){
            $v['feetype_name'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
            $v['jxss'] = 1;
            $v['pps'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->sum('brand');
            $v['sqje'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->sum('yjsjtrfy');
            $sjfykm[$k] = $v;
        }
        $this->assign('sjfykm',$sjfykm);

        $export = $this->request->get('export');
        if($export){

            //根据经销商查询分区省份和城市
            $city = db('cg_jxs t')->join('cg_market_city t2','t.city=t2.id')->where('t.id',$data['jxs_id'])->value('t2.title');
            $provice = db('cg_jxs t')->join('cg_market_provice t2','t.provice=t2.id')->where('t.id',$data['jxs_id'])->value('t2.title');
            $zoning = db('cg_jxs t')->join('cg_market_zoning t2','t.zoning=t2.id')->where('t.id',$data['jxs_id'])->value('t2.title');
            $this->assign([
                'city'=>$city,
                'provice'=>$provice,
                'zoning'=>$zoning,
            ]);

            ob_end_clean();
            ob_start();

            header('Content-Type : application/vnd.ms-excel');
            header('Content-Disposition:attachment;filename="'.iconv('utf-8','gbk',$data['sn'].'-'.date("Y年m月j日")).'.xls"');
            return $this->fetch('view_export');
        }else{
            //查询核销编号
            $hxsn = db('cg_ti_hexiao t')
                ->join('cg_ti_hexiao_list t2','t2.hx_id=t.id')
                ->join('cg_ti_list t3','t3.id=t2.list_id')
                ->where('t3.ti_id',$id)
                ->field('t.id,t.sn')
                ->select();
            $this->assign('hxsn',$hxsn);
            //查询反馈编号
            $fbsn = db('all_ti_feeback_list t')
                ->join('cg_ti t2','t2.id=t.apply_id')
                ->where(['type'=>1,'t2.id'=>$id])
                ->field('t.id,t.no')
                ->find();
            $this->assign('fbsn',$fbsn);

            //查询用户名和密码
            $login_name = db('users')->where('id',session('login_id'))->value('login_name');
            $login_pwd = db('users')->where('id',session('login_id'))->value('login_pwd');
            $this->assign('login_name',$login_name);
            $this->assign('login_pwd',$login_pwd);

            return $this->fetch();
        }
    }

    //压缩费用：非常规
    public function ysfy_fcg(){
        $ti_id = $this->request->post('ti_id');
        $feetype = $this->request->post('feetype/a');
        $hzje = $this->request->post('hzje/a');

        //验证输入
        foreach($hzje as $k=>$v){
            $valid = new Valid([
                'hzje|核准金额'=>'require|number|min:0'
            ]);
            if(!$valid->check(['hzje'=>$v])){
                echo json_encode(['success'=>false,'msg'=>$valid->getError()]);die;
            }
        }

        foreach($feetype as $k=>$v){
            $zyjsjtrfy = db('cg_ti_list')->where(['ti_id'=>$ti_id,'feetype'=>$v])->sum('yjsjtrfy');
            $zyjsjtrfy = $zyjsjtrfy?$zyjsjtrfy:1;
            $list = db('cg_ti_list')->where(['ti_id'=>$ti_id,'feetype'=>$v])->select();
            foreach($list as $k1=>$v1){
                $yjsjtrfy = db('cg_ti_list')->where('id',$v1['id'])->value('yjsjtrfy');
                $bili = $yjsjtrfy/$zyjsjtrfy;
                $hzje1 = round($hzje[$k]*$bili,2);
                db('cg_ti_list')->where('id',$v1['id'])->update(['hzje'=>$hzje1]);
            }
        }
        echo json_encode(['success'=>true,'msg'=>'压缩成功']);die;
    }

    //压缩费用：常规
    public function ysfy_cg(){
       $data=$this->request->post();
       //print_r($data);
       if(isset($data["ti_id"])){
            if(isset($data["feetype"])&&isset($data["hzje"])){
                //验证
                for($i=0;$i<count($data["feetype"]);$i++){
                    if(trim($data["hzje"][$i])===""){
                        return json_encode(["msg"=>"压缩金额不能为空","state"=>2]);
                    }
                    if(!trim($data["feetype"][$i])){
                        return json_encode(["msg"=>"请正确提交","state"=>2]);
                    }
                    try{
                        $data["hzje"][$i]=(float)$data["hzje"][$i];
                    }catch (\Exception $e) {
                        return json_encode(["msg"=>"请正确输入金额","state"=>2]);
                    }
                }
                //处理
                Db::startTrans();
                try{
                    for($i=0;$i<count($data["feetype"]);$i++){
                        $maxje=db("cg_ti_list")->where("ti_id={$data["ti_id"]} and feetype={$data["feetype"][$i]} and (isOrNo=1 or isOrNo is null)")->sum("hanshui");
                        if($maxje){
                            $bili=$data["hzje"][$i]/$maxje;
                            $feilist=db("cg_ti_list")->where("ti_id={$data["ti_id"]} and feetype={$data["feetype"][$i]} and (isOrNo=1 or isOrNo is null)")->select();
                            for($j=0;$j<count($feilist);$j++){
                                $up["id"]=$feilist[$j]["id"];
                                $up["pizhunhanshui"]=$feilist[$j]["hanshui"]*$bili;
                                $up["yjsjtrfy"]=$feilist[$j]["hanshui"]*$bili;
                                $shuilv= $feilist[$j]["shuilv"];
                                $up["pizhunweishui"]=$up["pizhunhanshui"]/(1+$shuilv/100);
                                $xl=$feilist[$j]["totalExpectedSales"];
                                $up["yujifeiyonglv"]=round($up["yjsjtrfy"]/$xl*100,2);
                                if($feilist[$j]["product"]){
                                    $profit=db("pro_products")->alias("p")
                                    ->join("pro_sku sk","p.sku_id=sk.id")
                                    ->join("pro_series s","sk.series_id=s.id")
                                    ->join("pro_category c","s.category_id=c.id")
                                    ->join("pro_brands b","c.brand_id=b.id")
                                    ->where(["p.id"=>$feilist[$j]["product"]])
                                    ->value("b.profit");
                                }else if($feilist[$j]["sku"]){
                                    $profit=db("pro_sku")->alias("sk")
                                    ->join("pro_series s","sk.series_id=s.id")
                                    ->join("pro_category c","s.category_id=c.id")
                                    ->join("pro_brands b","c.brand_id=b.id")
                                    ->where(["sk.id"=>$feilist[$j]["sku"]])
                                    ->value("b.profit");
                                }else if($feilist[$j]["series"]){
                                    $profit=db("pro_series")->alias("s")
                                    ->join("pro_category c","s.category_id=c.id")
                                    ->join("pro_brands b","c.brand_id=b.id")
                                    ->where(["s.id"=>$feilist[$j]["series"]])
                                    ->value("b.profit");
                                }else if($feilist[$j]["category"]){
                                    $profit=db("pro_category")->alias("c")
                                    ->join("pro_brands b","c.brand_id=b.id")
                                    ->where(["c.id"=>$feilist[$j]["category"]])
                                    ->value("b.profit");
                                }else{
                                     $profit=db("pro_brands")->where(["id"=>$feilist[$j]["brand"]])->value("profit");
                                }
                                
                                $base=$feilist[$j]["totalBenchmarkSales"];
                                if($up["pizhunhanshui"])
                                    $up["yujiroi"]=($xl-$base)*$profit/100/$up["pizhunhanshui"];
                                else
                                    $up["yujiroi"]=0;
                                db("cg_ti_list")->update($up);
                            }
                        }
                    }
                    //处理预算
                    $ys=db("yusuan")->alias("y")->join("yusuan_detail yd","yd.yid=y.id")->where("y.type=1 and yd.aid={$data["ti_id"]}")->field("yd.id")->select();
                    if($ys){
                        $ysstr=[];
                        for($i=0;$i<count($ys);$i++){
                            $ysstr[]=$ys[$i]["id"];
                        }
                        $ysstr=implode(',',$ysstr);
                        db("yusuan_detail")->where("id in ($ysstr)")->delete();
                    }
                    $newys=$this->tiys($data["ti_id"]);
                    if($newys)
                        db("yusuan_detail")->insertAll($newys);
                }catch (\Exception $e) {
                    Db::rollBack();
                    return json_encode(["msg"=>$e->getMessage(),"state"=>2]);
                }
                Db::commit(); return json_encode(["msg"=>"","state"=>1]);
            }else{
                return json_encode(["msg"=>"请正确提交","state"=>2]);
            }
       }else{
            return json_encode(["msg"=>"请正确提交","state"=>2]);
       }
    }

    //提交审批-非常规
    public function tjsp_fcg(){
        $id = $this->request->post('id');
        $sfxyfk = $this->request->post('sfxyfk');
        $sfxyfk = $sfxyfk?$sfxyfk:0;
        $bool = db('cg_ti')->where('id',$id)->update(['sfxyfk'=>$sfxyfk]);
        $attach = $temp =  $this->request->post('attach');
        $attach = $attach?serialize(explode(',',$attach)):null;
        $new_id = db('cg_workflow_spyj')->insertGetId([
            'spr_id'=>session('employee_id'),
            'spr_name'=>db('employee')->where('id',session('employee_id'))->value('em_name'),
            'spr_job'=>db('job t')->join('job_employee t2','t2.job_id=t.id')->where('t2.employee_id',session('employee_id'))->value('t.job_name'),
            'wf_id'=>db('cg_workflow')->where(['ywlx'=>2,'yw_id'=>$id])->value('id'),
            'spsj'=>date('Y-m-d H:i:s'),
            'attach'=>$attach,
        ]);
        db('annex')->where('id','in',$attach)->update(['target_table'=>'cg_workflow_spyj','target_id'=>$new_id]);
        if(false !== $bool){
            echo json_encode(['success'=>true,'msg'=>'提交成功']);die;
        }else{
            echo json_encode(['success'=>false,'msg'=>'提交失败']);die;
        }
    }

    //提交审批-常规
    public function tjsp_cg(){
        $request = Request::instance();
        $data = $request->post();
        //print_r($data);exit;
        $id = $data["id"];
        if(isset($data["sfxyfk"]))
            $sfxyfk = 1;
        else
           $sfxyfk = 0;
        //echo json_encode(['success'=>false,'msg'=>$sfxyfk]);die;
        try{
            $bool = db('cg_ti')->where('id',$id)->update(['sfxyfk'=>$sfxyfk]);
        }catch (\Exception $e) {
               
           echo json_encode(['success'=>false,'msg'=>'提交失败']);die;
        }
        
        echo json_encode(['success'=>true,'msg'=>'提交成功']);die;

    }
    //提交审批2
    public function tjsp_cg2(){
        $request = Request::instance();
        $data = $request->post();
        //print_r($data);exit;
        if(isset($data['list_id'])){
            Db::startTrans();
            try{
                for($i=0;$i<count($data["list_id"]);$i++){
                    $up["id"]=$data["list_id"][$i];
                    $up["paymethod"]=$data["fyzffs"][$i];
                    $up["sfyqhc"]=$data["sfyqhc"][$i];
                    $up["jrbm"]=$data["fyjrbm"][$i];
                    $up["project"]=$data["jrfa"][$i];
                    db("cg_ti_list")->update($up);
                }
                if(isset($data["sfxyfk"]))
                    $upd["sfxyfk"]=1;
                else
                    $upd["sfxyfk"]=0;
                $upd["id"]=db("cg_ti_list")->where(["id"=>$data["list_id"][0]])->value("ti_id");
                db("cg_ti")->update($upd);
            }catch (\Exception $e) {
                Db::rollBack();
                return json_encode(["msg"=>$e->getMessage(),"state"=>2]);
            }
                Db::commit();
                return json_encode(["msg"=>"","state"=>1]);
        }else{
            return json_encode(["msg"=>"请正确提交","state"=>2]);
        }
    }
    //根据id查找产品纬度值
    public function productlatval($v){
        if($v['brand']){
            return db('pro_brands')->where('id',$v['brand'])->value('brand_name');
        }elseif($v['category']){
            return db('pro_category')->where('id',$v['category'])->value('category_name');
        }elseif($v['series']){
            return db('pro_series')->where('id',$v['series'])->value('series_name');
        }elseif($v['sku']){
            return db('pro_sku')->where('id',$v['sku'])->value('sku_name');
        }elseif($v['product']){
            return db('pro_products')->where('id',$v['product'])->value('pro_name');
        }
    }
    public function feihedui($aid){
        //echo $aid;exit;
        $sjfykm = db('cg_ti_list')->where('ti_id',$aid)->field('feetype')->group('feetype')->select();
        $arr=[];$arr[1]=0;//总费用
        foreach($sjfykm as $k=>$v){
            $v['feetype_name'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
            $v['jxss'] = 1;
            $v['pps'] = db('cg_ti_list')->where(['ti_id'=>$aid,'feetype'=>$v['feetype']])->sum('brand');
            $v['sqje'] = db('cg_ti_list')->where(['ti_id'=>$aid,'feetype'=>$v['feetype']])->sum('pizhunhanshui');
            $sjfykm[$k] = $v;
            $arr[1]+=$v['sqje'];
        }
        $applyde=db("cg_ti_list")->where('ti_id',$aid)->field("yjsjtrfy as pizhunhanshui,totalExpectedSales,yujiroi")->select();
        $hanshui=0;$xl=0;$roi=0;
        for($i=0;$i<count($applyde);$i++){
            $hanshui+=$applyde[$i]["pizhunhanshui"];
            $xl+=$applyde[$i]["totalExpectedSales"];
            if($applyde[$i]["pizhunhanshui"])
                $roi+=$applyde[$i]["pizhunhanshui"]*$applyde[$i]["yujiroi"];
        }
        $fyl=$hanshui/$xl*100;
        if($hanshui)
            $roi=$roi/$hanshui;
        else
            $roi=0;
        $arr[0]=$sjfykm;$arr[2]=$fyl;$arr[3]=$roi;
        return json_encode($arr);
    }
    //常规申请明细
    public function formalapplymx(){
        $id = $this->request->param('id');
        $ti = db('cg_ti')->where('id',$id)->find();
        $ti['cuser_name'] = db('employee')->where('id',$ti['cuser'])->value('em_name');
        $ti['cuser_job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->where('t2.employee_id',$ti['cuser'])->value('t.job_name');
        $ti['cuser_de'] = db('department t')->join('department_employee t2','t2.department_id=t.id')->where('t2.employee_id',$ti['cuser'])->value('t.de_name');
        $ti['jxs_name'] = db('cg_jxs')->where('id',$ti['jxs_id'])->value('title');
        $ti['zoning'] = db('cg_market_zoning t')->join('cg_jxs t2','t2.zoning=t.id')->value('t.title');
        $ti['provice'] = db('cg_market_provice t')->join('cg_jxs t2','t2.provice=t.id')->value('t.title');
        $ti['city'] = db('cg_market_city t')->join('cg_jxs t2','t2.city=t.id')->value('t.title');
        $ti['direct'] = db('cg_jxs')->where('id',$ti['jxs_id'])->value('direct');
        $ti["state"]=db("ti_state")->where(["id"=>$ti["status"]])->value("title");
        $this->assign('ti',$ti);

        $applyde = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_ti_list yuanapd", "apd.refer_id=yuanapd.id", "LEFT")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")
            ->join("cg_system s", "n.system_id=s.id", "LEFT")
            ->join("pro_products p", "apd.product=p.id")
            ->join("pro_sku sk", "p.sku_id=sk.id")
            ->join("pro_series ps", "sk.series_id=ps.id")
            ->join("pro_category pc","ps.category_id=pc.id")
            ->join("pro_brands pb","pc.brand_id=pb.id")
            ->join("pro_price pp", "pp.pid=p.id")
            ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")
            ->join("cg_paymethod cp", "apd.paymethod=cp.id")
            ->join("cg_fijiru cf", "apd.project=cf.id")
            ->join("cg_fijiruzd fj", "apd.jrbm=fj.id")->join("department d", "fj.title=d.id")
            ->where(["ap.id" => $id])->order("apd.net_id,apd.product")
            ->field("ap.sn as no,apd.sn as detail_no,apd.net_id,apd.id as did,apd.is_bu,n.title as net,s.title as xitong,ps.series_name,p.pro_name,apd.start as start_time,apd.end as end_time,apd.expCanTime as  hexiao_time,apd.boxnum as sell_num,apd.bucha,p.unit,p.box_num,pp.factory,apd.yuan_price,apd.now_price,apd.wangdian_price,apd.lingshou_price,apd.huodong_price,f3.title as feiyong3,apd.amount as zonge,(apd.pizhunhanshui) as hanshui,apd.brief as beizhu,apd.head as fuzeren,cp.title as zffs,cf.title as jrfa,(apd.totalExpectedSales) as xiaoshoue,apd.feiyongmiaoshu as remark,d.de_name,apd.shuilv,apd.isVAT as dikou,apd.zhejia,apd.hx_yihexiao as hexiao,apd.paymethod as zfid,apd.status as tag,yuanapd.start  as yuanstart,yuanapd.end as yuanend,yuanapd.expCanTime as yuanhexiao,apd.ydreason,apd.cancel_reason,apd.fb_shijixiaoliang as fankuinum,(apd.now_price*p.box_num*apd.fb_shijixiaoliang) as shijixiaoshoue,(apd.fb_shijixiaoliang/apd.boxnum)*100 as xiaoliang,(apd.wangdian_price*apd.zhejia/100)*p.box_num*apd.fb_shijixiaoliang as zjzj,yuanapd.pizhunweishui  as yuanzonge,apd.pizhunweishui as  pifuzonge,apd.fb_shijiweishui as fankuijine,apd.fb_shijitourufeiyong as fankuihanshui,apd.product,apd.yjsjtrfy,apd.yujifeiyonglv,apd.totalBenchmarkSales,apd.yujiroi,apd.zhejia,apd.wangdian_zhejia,((apd.yuan_price-apd.now_price)*p.box_num*apd.bucha) as jxscha,apd.maoli,apd.wangdian_yuan,((apd.wangdian_yuan-apd.wangdian_price)*p.box_num*apd.bucha) as netcha,apd.netout,apd.huodongout,apd.wangdian_zhejia,apd.wangdianmaoli,apd.pizhunweishui,apd.yujifeiyonglv,pb.profit,apd.isOrNo,apd.sfyqhc,apd.jizhunboxnum")
            ->select();

        for ($i = 0; $i < count($applyde); $i++) {
            $applyde[$i]["start_time"] = date("Y-m-d", $applyde[$i]["start_time"]);
            $applyde[$i]["end_time"] = date("Y-m-d", $applyde[$i]["end_time"]);
            $applyde[$i]["hexiao_time"] = date("Y-m-d", $applyde[$i]["hexiao_time"]);
            if ($applyde[$i]["yuanstart"])
                $applyde[$i]["yuanstart"] = date("Y-m-d", $applyde[$i]["yuanstart"]);
            if ($applyde[$i]["yuanend"])
                $applyde[$i]["yuanend"] = date("Y-m-d", $applyde[$i]["yuanend"]);
            if ($applyde[$i]["yuanhexiao"])
                $applyde[$i]["yuanhexiao"] = date("Y-m-d", $applyde[$i]["yuanhexiao"]);
        }
        $this->assign('ti_list',$applyde);

        //费用支付方式
        $fyzffs = db('cg_paymethod')->select();
        $this->assign('fyzffs',$fyzffs);

        //费用计入方案
        $fyjrfa = db('cg_fijiru')->field('id,title')->select();
        $this->assign('fyjrfa',$fyjrfa);

        //费用计入部门
        $fyjrbm = db('cg_fijiruzd')->field('id,title')->select();
        foreach($fyjrbm as $k=>$v){
            $v['title'] = db('department')->where('id',$v['title'])->value('de_name');
            $fyjrbm[$k] = $v;
        }
        $this->assign('fyjrbm',$fyjrbm);

        //本申请包含网点数
        $wds = Db::query('select count(*) cnt from (select net_id from cg_ti_list where ti_id='.$id.' group by net_id) a');
        $this->assign('wds',$wds[0]['cnt']);

        //促销折让与折扣
        $cxzryzk = 0;
        $zfy = 0; //总费用
        $zyjxl = 0;//总预计销量
        $zongroi=0;//总roi
        foreach ($applyde as $item) {
            $spmxsl = db('pro_products')->where('id',$item['product'])->value('box_num');
            $t = $item['bucha']*$item['now_price']*$spmxsl*$item['zhejia']/100;
            $cxzryzk+=$t;
            $zfy += $item['yjsjtrfy'];
            $zyjxl += $item['xiaoshoue'];
            $zongroi+=$item["yujiroi"]*$item["yjsjtrfy"];
        }
        $zongroi=round($zongroi/$zfy,2);
        $this->assign("zongroi",$zongroi);
        $this->assign('cxzryzk',$cxzryzk);
        $this->assign('zfy',$zfy);
        $this->assign('zyjxl',$zyjxl);
        $zfyl = round($zfy/$zyjxl*100,2);
        $this->assign('zfyl',$zfyl);

        //按照三级费用科目查询
        $sjfykm = db('cg_ti_list')->where('ti_id',$id)->field('feetype')->group('feetype')->select();
        foreach($sjfykm as $k=>$v){
            $v['feetype_name'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
            $v['jxss'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->group("net_id")->count();;
            $v['pps'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->group("product")->count();
            $v['sqje'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->sum('pizhunhanshui');
            $v['maxje'] = db('cg_ti_list')->where("ti_id=$id and feetype={$v['feetype']} and (isOrNo=1 or isOrNo is null)")->sum('hanshui');
                if(!$v['maxje'])
                    $v['maxje'] = 0;
                else
                    $v['maxje']=round($v['maxje'],2);
            $sjfykm[$k] = $v;
        }
        $this->assign('sjfykm',$sjfykm);
//查询用户名和密码
        $login_name = db('users')->where('id',session('login_id'))->value('login_name');
        $login_pwd = db('users')->where('id',session('login_id'))->value('login_pwd');
        $this->assign('login_name',$login_name);
        $this->assign('login_pwd',$login_pwd);

       $logs=$this->getlog(3,$id);
       $this->assign("logs",$logs);
        return $this->fetch();
    }
     //获取审批信息
    public function getlog($fid,$aid){
        $result=[];
        $getwork=db('cg_workflow')->where(["ywlx"=>$fid,"yw_id"=>$aid])->value("workid");
        if($getwork){
            $result=Db::connect('db_config1')->name('tw_hz_log') 
            ->where(['workid'=>$getwork,"action"=>"submit"])
            ->select();
        }

        //print_r($result);
        return $result;
    }
    public function getformat($aid){
        $sjfykm = db('cg_ti_list')->where('ti_id',$aid)->field('feetype')->group('feetype')->select();
        $zong=0;
        foreach($sjfykm as $k=>$v){
            $v['feetype_name'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
            $v['maxje'] = db('cg_ti_list')->where("ti_id=$aid and feetype={$v['feetype']} and (isOrNo=1 or isOrNo is null)")->sum('hanshui');
                if(!$v['maxje'])
                    $v['maxje'] = 0;
                else
                    $v['maxje']=round($v['maxje'],2);
            $sjfykm[$k] = $v;
            $zong+=$v['maxje'];
        }
        $arr[0]=$sjfykm;
        $arr[1]=$zong;
        return json_encode($arr);
    }
    //常规申请明细--待阅
    public function formalapplymx2(){
        $id = $this->request->param('id');
        $ti = db('cg_ti')->where('id',$id)->find();
        $ti['cuser_name'] = db('employee')->where('id',$ti['cuser'])->value('em_name');
        $ti['cuser_job'] = db('job t')->join('job_employee t2','t2.job_id=t.id')->where('t2.employee_id',$ti['cuser'])->value('t.job_name');
        $ti['cuser_de'] = db('department t')->join('department_employee t2','t2.department_id=t.id')->where('t2.employee_id',$ti['cuser'])->value('t.de_name');
        $ti['jxs_name'] = db('cg_jxs')->where('id',$ti['jxs_id'])->value('title');
        $ti['zoning'] = db('cg_market_zoning t')->join('cg_jxs t2','t2.zoning=t.id')->value('t.title');
        $ti['provice'] = db('cg_market_provice t')->join('cg_jxs t2','t2.provice=t.id')->value('t.title');
        $ti['city'] = db('cg_market_city t')->join('cg_jxs t2','t2.city=t.id')->value('t.title');
        $ti['direct'] = db('cg_jxs')->where('id',$ti['jxs_id'])->value('direct');
        $this->assign('ti',$ti);

        $applyde = Db::table("cg_ti")->alias("ap")
            ->join("cg_ti_list apd", "apd.ti_id=ap.id")
            ->join("cg_ti_list yuanapd", "apd.refer_id=yuanapd.id", "LEFT")
            ->join("cg_net n", "apd.net_id=n.id", "LEFT")
            ->join("cg_system s", "n.system_id=s.id", "LEFT")
            ->join("pro_products p", "apd.product=p.id")
            ->join("pro_sku sk", "p.sku_id=sk.id")
            ->join("pro_series ps", "sk.series_id=ps.id")
            ->join("pro_price pp", "pp.pid=p.id")
            ->join("cg_feiyongkemu3 f3", "apd.feetype=f3.id")
            ->join("cg_paymethod cp", "apd.paymethod=cp.id")
            ->join("cg_fijiru cf", "apd.project=cf.id")
            ->join("cg_fijiruzd fj", "apd.jrbm=fj.id")->join("department d", "fj.title=d.id")
            ->where(["ap.id" => $id])->order("apd.net_id,apd.product")
            ->field("ap.sn as no,apd.sn as detail_no,apd.net_id,apd.id as did,apd.is_bu,n.title as net,s.title as xitong,ps.series_name,p.pro_name,apd.start as start_time,apd.end as end_time,apd.expCanTime as  hexiao_time,apd.totalExpectedSales as sell_num,apd.bucha,p.unit,p.box_num,pp.factory,apd.yuan_price,apd.now_price,apd.wangdian_price,apd.lingshou_price,apd.huodong_price,f3.title as feiyong3,apd.amount as zonge,(apd.pizhunhanshui) as hanshui,apd.brief as beizhu,apd.head as fuzeren,cp.title as zffs,cf.title as jrfa,(apd.now_price*p.box_num*apd.totalExpectedSales) as xiaoshoue,apd.feiyongmiaoshu as remark,d.de_name,apd.shuilv,apd.isVAT as dikou,apd.zhejia,apd.hx_yihexiao as hexiao,apd.paymethod as zfid,apd.status as tag,yuanapd.start  as yuanstart,yuanapd.end as yuanend,yuanapd.expCanTime as yuanhexiao,apd.ydreason,apd.cancel_reason,apd.fb_shijixiaoliang as fankuinum,(apd.now_price*p.box_num*apd.fb_shijixiaoliang) as shijixiaoshoue,(apd.fb_shijixiaoliang/apd.totalExpectedSales)*100 as xiaoliang,(apd.wangdian_price*apd.zhejia/100) as zj,(apd.wangdian_price-apd.wangdian_price*apd.zhejia/100) as wangcuxiao,(apd.wangdian_price*apd.zhejia/100)*p.box_num*apd.fb_shijixiaoliang as zjzj,yuanapd.pizhunweishui  as yuanzonge,apd.pizhunweishui as  pifuzonge,apd.fb_shijiweishui as fankuijine,apd.fb_shijitourufeiyong as fankuihanshui,apd.product,apd.yjsjtrfy")
            ->select();

        for ($i = 0; $i < count($applyde); $i++) {
            $applyde[$i]["start_time"] = date("Y-m-d", $applyde[$i]["start_time"]);
            $applyde[$i]["end_time"] = date("Y-m-d", $applyde[$i]["end_time"]);
            $applyde[$i]["hexiao_time"] = date("Y-m-d", $applyde[$i]["hexiao_time"]);
            if ($applyde[$i]["yuanstart"])
                $applyde[$i]["yuanstart"] = date("Y-m-d", $applyde[$i]["yuanstart"]);
            if ($applyde[$i]["yuanend"])
                $applyde[$i]["yuanend"] = date("Y-m-d", $applyde[$i]["yuanend"]);
            if ($applyde[$i]["yuanhexiao"])
                $applyde[$i]["yuanhexiao"] = date("Y-m-d", $applyde[$i]["yuanhexiao"]);
        }
        $this->assign('ti_list',$applyde);

        //费用支付方式
        $fyzffs = db('cg_paymethod')->select();
        $this->assign('fyzffs',$fyzffs);

        //费用计入方案
        $fyjrfa = db('cg_fijiru')->field('id,title')->select();
        $this->assign('fyjrfa',$fyjrfa);

        //费用计入部门
        $fyjrbm = db('cg_fijiruzd')->field('id,title')->select();
        foreach($fyjrbm as $k=>$v){
            $v['title'] = db('department')->where('id',$v['title'])->value('de_name');
            $fyjrbm[$k] = $v;
        }
        $this->assign('fyjrbm',$fyjrbm);

        //本申请包含网点数
        $wds = Db::query('select count(*) cnt from (select net_id from cg_ti_list where ti_id='.$id.' group by net_id) a');
        $this->assign('wds',$wds[0]['cnt']);

        //促销折让与折扣
        $cxzryzk = 0;
        $zfy = 0; //总费用
        $zyjxl = 0;//总预计销量
        foreach ($applyde as $item) {
            $spmxsl = db('pro_products')->where('id',$item['product'])->value('box_num');
            $t = $item['bucha']*$item['now_price']*$spmxsl*$item['zhejia']/100;
            $cxzryzk+=$t;
            $zfy += $item['yjsjtrfy'];
            $zyjxl += $item['sell_num'];
        }
        $this->assign('cxzryzk',$cxzryzk);
        $this->assign('zfy',$zfy);
        $this->assign('zyjxl',$zyjxl);
        $zfyl = round($zfy/$zyjxl*100,2);
        $this->assign('zfyl',$zfyl);

        //按照三级费用科目查询
        $sjfykm = db('cg_ti_list')->where('ti_id',$id)->field('feetype')->group('feetype')->select();
        foreach($sjfykm as $k=>$v){
            $v['feetype_name'] = db('cg_feiyongkemu3')->where('id',$v['feetype'])->value('title');
            $v['jxss'] = 1;
            $v['pps'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->sum('brand');
            $v['sqje'] = db('cg_ti_list')->where(['ti_id'=>$id,'feetype'=>$v['feetype']])->sum('yjsjtrfy');

            $sjfykm[$k] = $v;
        }
        $this->assign('sjfykm',$sjfykm);
//查询用户名和密码
        $login_name = db('users')->where('id',session('login_id'))->value('login_name');
        $login_pwd = db('users')->where('id',session('login_id'))->value('login_pwd');
        $this->assign('login_name',$login_name);
        $this->assign('login_pwd',$login_pwd);

        //查询审批意见
        $workId = db('cg_workflow')->where(['ywlx'=>3,'yw_id'=>$id])->value('workId');
        //获取操作记录
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['workId'] = $workId;
        $spyj = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/history.wf',$post_data);
        $spyj = object_array($spyj);
        $this->assign('spyj',$spyj);

        return $this->fetch();
    }

    //办理人
    public function blr(){
        $data = db('users t')->join('employee t2','t2.id=t.employee_id')->field('t.id,t2.em_name')->select();
        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }

    //任意退回
    public function ryth(){
        $nodeId = $this->request->post('nodeId');
        $workId = $this->request->post('workId');
        $trackId = $this->request->post('trackId');
        $actionData = [
            'operate'=>'submit',
            'operateClazz'=>'com.horizon.wf.action.ActionRejectByJump',
            'operateText'=>'任意退回',
            'operateFlag'=>1,
        ];
        $param = [
            'accessToken'=>session("accessToken"),
            'workId'=>$workId,
            'trackId'=>$trackId,
            'nodeId'=>$nodeId,
            'actionData'=>$actionData,
        ];
        $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/flow/support/action.wf',$param);

        $data = object_array($data);
        echo json_encode(['data'=>$data,'msg'=>'ok']);die;
    }
    //工作流审批状态查询
    public function checkstate(){
        $workId=$this->request->param("workId");
        $trackId=$this->request->param("trackId");
        $yw=db("cg_workflow")->where(["workId"=>$workId,"trackId"=>$trackId])->field("ywlx,yw_id")->find();
        $now_state=0;
        switch ($yw["ywlx"]) {
            case '1':
            case '2':
            case '3':
            case '21':
            case '22':
            case '24':
                $now_state=db("cg_ti")->where(["id"=>$yw["yw_id"]])->value("status");
                break;
            case '5':
                $now_state=db("chuchai_apply")->where(["id"=>$yw["yw_id"]])->value("state");
                break;
            case '6':
                $now_state=db("wanneng_apply")->where(["id"=>$yw["yw_id"]])->value("state");
                break;
            case '7':
                $now_state=db("jxs_hetong")->where(["id"=>$yw["yw_id"]])->value("state");
                break;
            case '8':
            case '9':
                $now_state=db("target_apply")->where(["id"=>$yw["yw_id"]])->value("state");
                break;
            case '10':
                $now_state=db("rc_baoxiao_apply")->where(["id"=>$yw["yw_id"]])->value("state");
                break;
            case '11':
            case '12':
            case '13':
                $now_state=db("ap_apply")->where(["id"=>$yw["yw_id"]])->value("state");
                break;
            case '14':
                $now_state=db("ap_fankui")->where(["id"=>$yw["yw_id"]])->value("state");break;
            case '15':
                $now_state=db("ap_hexiao_apply")->where(["id"=>$yw["yw_id"]])->value("state");break;
            case '16':
            case '19':
                $now_state=db("apti_fp_apply")->where(["id"=>$yw["yw_id"]])->value("state");break;
            case '17':
                $now_state=db("all_ti_feeback_list")->where(["id"=>$yw["yw_id"]])->value("state");break;
            case '18':
                $now_state=db("cg_ti_hexiao")->where(["id"=>$yw["yw_id"]])->value("status");break;
            case '20':
                $now_state=db("cg_channel_preferential_policy")->where(["id"=>$yw["yw_id"]])->value("status");break;
            case '23':
                $now_state=db("cg_order")->where(["id"=>$yw["yw_id"]])->value("status");break;
            case '25':
            case '26':
                $now_state=db("target_net_apply")->where(["id"=>$yw["yw_id"]])->value("state");
                break;
            case '27':
                $now_state=db("yd_qjsq")->where(["id"=>$yw["yw_id"]])->value("state");
                break;
            case '28':
                $now_state=db("jiaban_apply")->where(["id"=>$yw["yw_id"]])->value("state");
                break;
            default:
                # code...
                break;
        }
        return $now_state;
    }
    //工作流审批
    public function gzlsp(){
        //查询用户名和密码
        $login_name = db('users')->where('id',session('login_id'))->value('login_name');
        /*if($login_name=="B")
            $login_name="A";*/
        $login_pwd = db('users')->where('id',session('login_id'))->value('login_pwd');
        $accessToken=session('accessToken');
        $this->assign("accessToken",$accessToken);
        $url=config('workflow_url');
        $workId=$this->request->param("workId");
        $trackId=$this->request->param("trackId");
        $yw=db("cg_workflow")->where(["workId"=>$workId,"trackId"=>$trackId])->field("ywlx,yw_id")->find();
        $now_state=0;
        switch ($yw["ywlx"]) {
            case '1':
            case '2':
            case '3':
            case '21':
            case '22':
            case '24':
                $now_state=db("cg_ti")->where(["id"=>$yw["yw_id"]])->value("status");
                break;
            case '5':
                $now_state=db("chuchai_apply")->where(["id"=>$yw["yw_id"]])->value("state");
                break;
            case '6':
                $now_state=db("wanneng_apply")->where(["id"=>$yw["yw_id"]])->value("state");
                break;
            case '7':
                $now_state=db("jxs_hetong")->where(["id"=>$yw["yw_id"]])->value("state");
                break;
            case '8':
            case '9':
                $now_state=db("target_apply")->where(["id"=>$yw["yw_id"]])->value("state");
                break;
            case '10':
                $now_state=db("rc_baoxiao_apply")->where(["id"=>$yw["yw_id"]])->value("state");
                break;
            case '11':
            case '12':
            case '13':
                $now_state=db("ap_apply")->where(["id"=>$yw["yw_id"]])->value("state");
                break;
            case '14':
                $now_state=db("ap_fankui")->where(["id"=>$yw["yw_id"]])->value("state");break;
            case '15':
                $now_state=db("ap_hexiao_apply")->where(["id"=>$yw["yw_id"]])->value("state");break;
            case '16':
            case '19':
                $now_state=db("apti_fp_apply")->where(["id"=>$yw["yw_id"]])->value("state");break;
            case '17':
                $now_state=db("all_ti_feeback_list")->where(["id"=>$yw["yw_id"]])->value("state");break;
            case '18':
                $now_state=db("cg_ti_hexiao")->where(["id"=>$yw["yw_id"]])->value("status");break;
            case '20':
                $now_state=db("cg_channel_preferential_policy")->where(["id"=>$yw["yw_id"]])->value("status");break;
            case '23':
                $now_state=db("cg_order")->where(["id"=>$yw["yw_id"]])->value("status");break;
            case '25':
            case '26':
                $now_state=db("target_net_apply")->where(["id"=>$yw["yw_id"]])->value("state");
                break;
            case '27':
                $now_state=db("yd_qjsq")->where(["id"=>$yw["yw_id"]])->value("state");
                break;
            case '28':
                $now_state=db("jiaban_apply")->where(["id"=>$yw["yw_id"]])->value("state");
                break;
            default:
                # code...
                break;
        }
        $this->assign("now_state",$now_state);
        $this->assign("url",$url);
        $this->assign('login_name',$login_name);
        $this->assign('login_pwd',$login_pwd);
        $post_data = [];
        $post_data['accessToken'] = session('accessToken');
        $post_data['requestType'] = 'TodoList';
       

        $data = $this->curl_post(config('workflow_url').'/horizon/workflow/rest/todo/page.wf',$post_data);
        
        $hasdb=0;
        foreach ($data->data as $k => $v) {
            # code...
            if( $v->workId==$workId){
                $hasdb=1;break;
            }
        }
        $this->assign("hasdb",$hasdb);
        //print_r($data);die;
        return $this->fetch();
    }
   //单条明细预算匹配
    public function tidys($did){
        $applyde=Db::table("cg_ti_list")->where(["id"=>$did])->select();
        $aid=$applyde[0]["ti_id"];
        $apply=Db::table("cg_ti")->where(["id"=>$aid])->find();
        $type_id=$apply["type_id"];
        $aptar=Db::table("target_format")->where(["type_id"=>2])->find();
        $jxs=Db::table("cg_jxs")->where(["id"=>$apply["jxs_id"]])->field("zoning,provice,city")->find();
        if($aptar){
            $yusuan=[];

            for($i=0;$i<count($applyde);$i++){
               // echo $i;
               if($type_id==1){
                    $applyde[$i]["product"]=$applyde[$i]["f1"];
                    $year=$applyde[$i]["year"];
                    $month=$applyde[$i]["month"];
                    $applyde[$i]["start"]=strtotime("{$year}-{$month}-15");
                    $applyde[$i]["end"]=strtotime("{$year}-{$month}-15");
                }
                if($applyde[$i]["product"]){
                    $applyde[$i]["sku"]=Db::table("pro_products")->where(["id"=>$applyde[$i]["product"]])->value("sku_id");
                }
                if($applyde[$i]["sku"]){
                    $applyde[$i]["series"]=Db::table("pro_sku")->where(["id"=>$applyde[$i]["sku"]])->value("series_id");
                }
                if($applyde[$i]["series"]){
                    $applyde[$i]["category"]=Db::table("pro_series")->where(["id"=>$applyde[$i]["series"]])->value("category_id");
                }
                if($applyde[$i]["category"]){
                    $applyde[$i]["brand"]=Db::table("pro_category")->where(["id"=>$applyde[$i]["category"]])->value("brand_id");
                }
                $applyde[$i]["jxs"]=$apply["jxs_id"];
                $applyde[$i]["fenqu"]=$jxs["zoning"];
                $applyde[$i]["sheng"]=$jxs["provice"];
                $applyde[$i]["shi"]=$jxs["city"];
                $where="type=1 ";
                $sanjifeiyong=$applyde[$i]["feetype"];
                $erjifeiyong=Db::table("cg_feiyongkemu3")->where(["id"=>$sanjifeiyong])->value("pid");
                $yijifeiyong=Db::table("cg_feiyongkemu2")->where(["id"=>$erjifeiyong])->value("pid");
                $channel=Db::table("cg_feiyongkemu3")->where(["id"=>$sanjifeiyong])->value("channeltypes");
                $channel=unserialize($channel);
                $channelstr=implode(',',$channel);
                //print_r($channel);exit;
                $start=$applyde[$i]["start"];
                $end=$applyde[$i]["end"];
                $tianshu=($end-$start)/24/3600+1;
                if($aptar["product_id"]){
                    if($aptar["product_id"]==11){
                        $where.="and pinpai={$applyde[$i]["brand"]} and pinlei is null and xilie is null ";
                    }else if($aptar["product_id"]==12){
                        if($applyde[$i]["category"]){
                            $where.="and pinpai={$applyde[$i]["brand"]} and pinlei={$applyde[$i]["category"]} and xilie is null ";
                        }else{
                            $where.="and pinpai=-1 ";
                        }
                    }else if($aptar["product_id"]==13){
                        if($applyde[$i]["series"]){
                            $where.="and pinpai={$applyde[$i]["brand"]} and pinlei={$applyde[$i]["category"]} and xilie={$applyde[$i]["series"]} ";
                        }else{
                            $where.="and pinpai=-1 ";
                        }
                    }
                }else{
                    $where.="and pinpai is null and pinlei is null and xilie is null ";
                }  
                if($aptar["area_id"]||$aptar["client_id"]){
                    if($aptar["area_id"]==20){
                        $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng is null and shi is null and jingxiao is null ";
                    }else if($aptar["area_id"]==21){
                        if($applyde[$i]["sheng"]){
                            $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng={$applyde[$i]["sheng"]} and shi is null and jingxiao is null ";
                        }else{
                            $where.="and fenqu=-1 ";
                        }
                    }else if($aptar["area_id"]==22){
                        if($applyde[$i]["shi"]){
                            $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng={$applyde[$i]["sheng"]} and shi={$applyde[$i]["shi"]} and jingxiao is null ";
                        }else{
                            $where.="and fenqu=-1 ";
                        }
                    }else if($aptar["client_id"]==8){
                        if($applyde[$i]["jxs"]){
                            $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng={$applyde[$i]["sheng"]} and shi={$applyde[$i]["shi"]} and jingxiao={$applyde[$i]["jxs"]} ";
                        }else{
                            $where.="and fenqu=-1 ";
                        }
                    }
                }else{
                    $where.="and fenqu is null and sheng is null and shi is null and jingxiao is null ";
                }
                if($aptar["feiyong_id"]){
                    if($aptar["feiyong_id"]==16){
                        $where.="and sanjifeiyong=$sanjifeiyong ";
                    }else if($aptar["feiyong_id"]==15){
                        $where.="and erjifeiyong=$erjifeiyong and sanjifeiyong is null ";
                    }else{
                        $where.="and yijifeiyong=$yijifeiyong and erjifeiyong is null and sanjifeiyong is null ";
                    }
                }else{
                    $where.="and yijifeiyong is null and erjifeiyong is null and sanjifeiyong is null ";
                }
               /* 
                if($aptar["channel_id"]){
                    $where.="and channel1 in ($channelstr) ";
                }*/
               //echo $where;
               if($aptar["kaoheqi"]==18){
                ///echo "---";
                    //二级考核期
                    $kaohes=Db::table("cg_kaoheqi2")->alias("k2")->join("cg_kaoheqi1 k1","k2.pid=k1.id")->where("k2.endtime>=$start and k2.starttime<=$end")->field("k2.id,k2.title,k2.pid,k1.cid,k2.starttime,k2.endtime")->select();
                    $hask=[];
                    for($j=0;$j<count($kaohes);$j++){
                        $hask[]=$kaohes[$j]["id"];
                    }
                    $kstr=implode(',',$hask);
                     $maxc=0;$maxcys=0;
                    for($j=0;$j<count($channel);$j++){
                        $tmpwhere=$where."and channel1={$channel[$j]} and erjikaoheqi in ($kstr) ";
                       // echo $tmpwhere."<br/>";
                        $tmpys=Db::table("yusuan")->where($tmpwhere)->sum("jine");
                        if($tmpys){
                            if($tmpys>$maxc){
                                $maxc=$channel[$j];
                                $maxcys=$tmpys;
                            }
                        }else{
                            $tmpys=0;
                        }
                    }
                     if($maxc){
                        //echo $maxc;
                        $where.="and channel1=$maxc ";
                        for($j=0;$j<count($kaohes);$j++){
                            $jisuanstart=$kaohes[$j]["starttime"]>=$start?$kaohes[$j]["starttime"]:$start;
                            $jisuanend=$kaohes[$j]["endtime"]<=$end?$kaohes[$j]["endtime"]:$end;
                            $ts=($jisuanend-$jisuanstart)/24/3600+1;
                            //echo "-".$ts;
                            $fullwhere=$where."and cainian={$kaohes[$j]["cid"]} and yijikaoheqi={$kaohes[$j]["pid"]} and erjikaoheqi={$kaohes[$j]["id"]}";
                            //echo $fullwhere;echo "<br/>";//exit;
                            $yusuanpipei=Db::table("yusuan")->where($fullwhere)->find();
                            if($yusuanpipei){
                                $hanshui=($applyde[$i]["yjsjtrfy"])/$tianshu*$ts;
                                $tmpy=["yid"=>$yusuanpipei["id"],"did"=>$applyde[$i]["id"],"aid"=>$aid,"jine"=>$hanshui,"type"=>1,"tianshu"=>$ts,"zongtianshu"=>$tianshu];
                                $yusuan[]=$tmpy;
                            }
                        }
                    }else{
                       // break;
                    }
                }else{
                   // echo "---";
                    //一级考核期
                    $kaohes=Db::table("cg_kaoheqi1")->where("endtime>=$start and starttime<=$end")->field("id,title,cid,starttime,endtime")->select();
                    $hask=[];
                    for($j=0;$j<count($kaohes);$j++){
                        $hask[]=$kaohes[$j]["id"];
                    }
                    $kstr=implode(',',$hask);
                    $maxc=0;$maxcys=0;
                    for($j=0;$j<count($channel);$j++){
                        $tmpwhere=$where."and channel1={$channel[$j]} and yijikaoheqi in ($kstr) ";
                        //echo $tmpwhere."<br/>";
                        $tmpys=Db::table("yusuan")->where($tmpwhere)->sum("jine");
                        if($tmpys){
                            if($tmpys>$maxc){
                                $maxc=$channel[$j];
                                $maxcys=$tmpys;
                            }
                        }else{
                            $tmpys=0;
                        }
                        //echo $tmpys."<br>";
                    }
                    if($maxc){
                        //echo $maxc;
                        $where.="and channel1=$maxc ";
                        for($j=0;$j<count($kaohes);$j++){
                            $jisuanstart=$kaohes[$j]["starttime"]>=$start?$kaohes[$j]["starttime"]:$start;
                            $jisuanend=$kaohes[$j]["endtime"]<=$end?$kaohes[$j]["endtime"]:$end;
                            $ts=($jisuanend-$jisuanstart)/24/3600+1;
                            //echo "-".$ts;
                            $fullwhere=$where."and cainian={$kaohes[$j]["cid"]} and  yijikaoheqi={$kaohes[$j]["id"]} and erjikaoheqi is null";
                            //echo $fullwhere;echo "<br/>";
                            $yusuanpipei=Db::table("yusuan")->where($fullwhere)->find();
                            if($yusuanpipei){
                                $hanshui=($applyde[$i]["yjsjtrfy"])/$tianshu*$ts;
                                $tmpy=["yid"=>$yusuanpipei["id"],"did"=>$applyde[$i]["id"],"aid"=>$aid,"jine"=>$hanshui,"type"=>1,"tianshu"=>$ts,"zongtianshu"=>$tianshu];
                                $yusuan[]=$tmpy;
                            }
                        }
                    }else{
                       // break;
                    }

                } 
            }
            //print_r($yusuan);exit;
            return $yusuan;
        }else{
            return [];//未设定格式
        }
    }
    //ti预算匹配
    public function tiys($aid){
        $apply=Db::table("cg_ti")->where(["id"=>$aid])->find();
        $applyde=Db::table("cg_ti_list")->where(["ti_id"=>$aid])->select();
         $type_id=$apply["type_id"];
        $aptar=Db::table("target_format")->where(["type_id"=>2])->find();
        $jxs=Db::table("cg_jxs")->where(["id"=>$apply["jxs_id"]])->field("zoning,provice,city")->find();
        if($aptar){
            $yusuan=[];
           //echo count($applyde);exit;
            for($i=0;$i<count($applyde);$i++){
                //echo $i;
                if($type_id==1){
                    $applyde[$i]["product"]=$applyde[$i]["f1"];
                    $year=$applyde[$i]["year"];
                    $month=$applyde[$i]["month"];
                    $applyde[$i]["start"]=strtotime("{$year}-{$month}-15");
                    $applyde[$i]["end"]=strtotime("{$year}-{$month}-15");
                }
                if($applyde[$i]["product"]){
                    $applyde[$i]["sku"]=Db::table("pro_products")->where(["id"=>$applyde[$i]["product"]])->value("sku_id");
                }
                if($applyde[$i]["sku"]){
                    $applyde[$i]["series"]=Db::table("pro_sku")->where(["id"=>$applyde[$i]["sku"]])->value("series_id");
                }
                if($applyde[$i]["series"]){
                    $applyde[$i]["category"]=Db::table("pro_series")->where(["id"=>$applyde[$i]["series"]])->value("category_id");
                }
                if($applyde[$i]["category"]){
                    $applyde[$i]["brand"]=Db::table("pro_category")->where(["id"=>$applyde[$i]["category"]])->value("brand_id");
                }
                $applyde[$i]["jxs"]=$apply["jxs_id"];
                $applyde[$i]["fenqu"]=$jxs["zoning"];
                $applyde[$i]["sheng"]=$jxs["provice"];
                $applyde[$i]["shi"]=$jxs["city"];
                $where="type=1 ";
                $sanjifeiyong=$applyde[$i]["feetype"];
                $erjifeiyong=Db::table("cg_feiyongkemu3")->where(["id"=>$sanjifeiyong])->value("pid");
                $yijifeiyong=Db::table("cg_feiyongkemu2")->where(["id"=>$erjifeiyong])->value("pid");
                $channel=Db::table("cg_feiyongkemu3")->where(["id"=>$sanjifeiyong])->value("channeltypes");
                $channel=unserialize($channel);
                $channelstr=implode(',',$channel);
                //print_r($channel);exit;
                $start=$applyde[$i]["start"];
                $end=$applyde[$i]["end"];
                $tianshu=($end-$start)/24/3600+1;
                if($aptar["product_id"]){
                    if($aptar["product_id"]==11){
                        $where.="and pinpai={$applyde[$i]["brand"]} and pinlei is null and xilie is null ";
                    }else if($aptar["product_id"]==12){
                        if($applyde[$i]["category"]){
                            $where.="and pinpai={$applyde[$i]["brand"]} and pinlei={$applyde[$i]["category"]} and xilie is null ";
                        }else{
                            $where.="and pinpai=-1 ";
                        }
                    }else if($aptar["product_id"]==13){
                        if($applyde[$i]["series"]){
                            $where.="and pinpai={$applyde[$i]["brand"]} and pinlei={$applyde[$i]["category"]} and xilie={$applyde[$i]["series"]} ";
                        }else{
                            $where.="and pinpai=-1 ";
                        }
                    }
                }else{
                    $where.="and pinpai is null and pinlei is null and xilie is null ";
                }  
                if($aptar["area_id"]||$aptar["client_id"]){
                    if($aptar["area_id"]==20){
                        $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng is null and shi is null and jingxiao is null ";
                    }else if($aptar["area_id"]==21){
                        if($applyde[$i]["sheng"]){
                            $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng={$applyde[$i]["sheng"]} and shi is null and jingxiao is null ";
                        }else{
                            $where.="and fenqu=-1 ";
                        }
                    }else if($aptar["area_id"]==22){
                        if($applyde[$i]["shi"]){
                            $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng={$applyde[$i]["sheng"]} and shi={$applyde[$i]["shi"]} and jingxiao is null ";
                        }else{
                            $where.="and fenqu=-1 ";
                        }
                    }else if($aptar["client_id"]==8){
                        if($applyde[$i]["jxs"]){
                            $where.="and fenqu={$applyde[$i]["fenqu"]} and sheng={$applyde[$i]["sheng"]} and shi={$applyde[$i]["shi"]} and jingxiao={$applyde[$i]["jxs"]} ";
                        }else{
                            $where.="and fenqu=-1 ";
                        }
                    }
                }else{
                    $where.="and fenqu is null and sheng is null and shi is null and jingxiao is null ";
                }
                if($aptar["feiyong_id"]){
                    if($aptar["feiyong_id"]==16){
                        $where.="and sanjifeiyong=$sanjifeiyong ";
                    }else if($aptar["feiyong_id"]==15){
                        $where.="and erjifeiyong=$erjifeiyong and sanjifeiyong is null ";
                    }else{
                        $where.="and yijifeiyong=$yijifeiyong and erjifeiyong is null and sanjifeiyong is null ";
                    }
                }else{
                    $where.="and yijifeiyong is null and erjifeiyong is null and sanjifeiyong is null ";
                }
               /* 
                if($aptar["channel_id"]){
                    $where.="and channel1 in ($channelstr) ";
                }*/
               //echo $where;echo "<br/>";
               if($aptar["kaoheqi"]==18){
                ///echo "---";
                    //二级考核期
                    $kaohes=Db::table("cg_kaoheqi2")->alias("k2")->join("cg_kaoheqi1 k1","k2.pid=k1.id")->where("k2.endtime>=$start and k2.starttime<=$end")->field("k2.id,k2.title,k2.pid,k1.cid,k2.starttime,k2.endtime")->select();
                    $hask=[];
                    for($j=0;$j<count($kaohes);$j++){
                        $hask[]=$kaohes[$j]["id"];
                    }
                    $kstr=implode(',',$hask);
                     $maxc=0;$maxcys=0;
                    for($j=0;$j<count($channel);$j++){
                        $tmpwhere=$where."and channel1={$channel[$j]} and erjikaoheqi in ($kstr) ";
                       // echo $tmpwhere."<br/>";
                        $tmpys=Db::table("yusuan")->where($tmpwhere)->sum("jine");
                        if($tmpys){
                            if($tmpys>$maxc){
                                $maxc=$channel[$j];
                                $maxcys=$tmpys;
                            }
                        }else{
                            $tmpys=0;
                        }
                    }
                     if($maxc){
                        //echo $maxc;
                        $where.="and channel1=$maxc ";
                        for($j=0;$j<count($kaohes);$j++){
                            $jisuanstart=$kaohes[$j]["starttime"]>=$start?$kaohes[$j]["starttime"]:$start;
                            $jisuanend=$kaohes[$j]["endtime"]<=$end?$kaohes[$j]["endtime"]:$end;
                            $ts=($jisuanend-$jisuanstart)/24/3600+1;
                            //echo "-".$ts;
                            $fullwhere=$where."and cainian={$kaohes[$j]["cid"]} and yijikaoheqi={$kaohes[$j]["pid"]} and erjikaoheqi={$kaohes[$j]["id"]}";
                            //echo $fullwhere;echo "<br/>";//exit;
                            $yusuanpipei=Db::table("yusuan")->where($fullwhere)->find();
                            if($yusuanpipei){
                                $hanshui=($applyde[$i]["yjsjtrfy"])/$tianshu*$ts;
                                $tmpy=["yid"=>$yusuanpipei["id"],"did"=>$applyde[$i]["id"],"aid"=>$aid,"jine"=>$hanshui,"type"=>1,"tianshu"=>$ts,"zongtianshu"=>$tianshu];
                                $yusuan[]=$tmpy;
                            }
                        }
                    }else{
                       // break;
                    }
                }else{
                   // echo "---";
                    //一级考核期
                    $kaohes=Db::table("cg_kaoheqi1")->where("endtime>=$start and starttime<=$end")->field("id,title,cid,starttime,endtime")->select();
                    $hask=[];
                    for($j=0;$j<count($kaohes);$j++){
                        $hask[]=$kaohes[$j]["id"];
                    }
                    $kstr=implode(',',$hask);
                    $maxc=0;$maxcys=0;
                    for($j=0;$j<count($channel);$j++){
                        $tmpwhere=$where."and channel1={$channel[$j]} and yijikaoheqi in ($kstr) ";
                        //echo $tmpwhere."<br/>";
                        $tmpys=Db::table("yusuan")->where($tmpwhere)->sum("jine");
                        if($tmpys){
                            if($tmpys>$maxc){
                                $maxc=$channel[$j];
                                $maxcys=$tmpys;
                            }
                        }else{
                            $tmpys=0;
                        }
                        //echo $tmpys."<br>";
                    }
                    if($maxc){
                        //echo $maxc;
                        $where.="and channel1=$maxc ";
                        for($j=0;$j<count($kaohes);$j++){
                            $jisuanstart=$kaohes[$j]["starttime"]>=$start?$kaohes[$j]["starttime"]:$start;
                            $jisuanend=$kaohes[$j]["endtime"]<=$end?$kaohes[$j]["endtime"]:$end;
                            $ts=($jisuanend-$jisuanstart)/24/3600+1;
                            //echo "-".$ts;
                            $fullwhere=$where."and cainian={$kaohes[$j]["cid"]} and  yijikaoheqi={$kaohes[$j]["id"]} and erjikaoheqi is null";
                            //echo $fullwhere;echo "<br/>";
                            $yusuanpipei=Db::table("yusuan")->where($fullwhere)->find();
                            if($yusuanpipei){
                                $hanshui=($applyde[$i]["yjsjtrfy"])/$tianshu*$ts;
                                $tmpy=["yid"=>$yusuanpipei["id"],"did"=>$applyde[$i]["id"],"aid"=>$aid,"jine"=>$hanshui,"type"=>1,"tianshu"=>$ts,"zongtianshu"=>$tianshu];
                                $yusuan[]=$tmpy;
                            }
                        }
                    }else{
                       // break;
                    }

                } 
              //  echo $i;
            }
            //print_r($yusuan);exit;
            return $yusuan;
        }else{
            return 0;//未设定格式
        }
       
    }
}